def wordCount(s: str) -> int:
return len(s.split())
def sortByWordCount(lst: list[str]) -> None:
lst.sort(key=wordCount)
x = [
"You don't need long words to sound smart, you just need good thinky smart parts.",
"Antidisestablishmentarianism is a long word, but not as long as pneumonoultramicroscopicsilicovolcanoconiosis!"
]
sortByWordCount(x)
print(x)
['Antidisestablishmentarianism is a long word, but not as long as pneumonoultramicroscopicsilicovolcanoconiosis!', "You don't need long words to sound smart, you just need good thinky smart parts."]
import typing
info: dict[str, typing.Any] = {
"surname": "Richards",
"given name": "Gregor",
"height": 1.76,
"employer": "University of Waterloo",
"alma mater": "Purdue University",
"graduation year": 2014,
"employment years": 11
}
info["employment years"] = info["employment years"] + 1
print(info)
{'surname': 'Richards', 'given name': 'Gregor', 'height': 1.76, 'employer': 'University of Waterloo', 'alma mater': 'Purdue University', 'graduation year': 2014, 'employment years': 13}
print(info["citizenship"])
--------------------------------------------------------------------------- KeyError Traceback (most recent call last) Input In [9], in <cell line: 1>() ----> 1 print(info["citizenship"]) KeyError: 'citizenship'
info["citizenship"] = "USA" # my great shame
print(info["citizenship"])
print(info)
USA
{'surname': 'Richards', 'given name': 'Gregor', 'height': 1.76, 'employer': 'University of Waterloo', 'alma mater': 'Purdue University', 'graduation year': 2014, 'employment years': 13, 'citizenship': 'USA'}
if "age" in info:
print("This person is", info["age"], "years old")
info.pop("employer") # fired for tormenting Science students
print(info["employer"])
--------------------------------------------------------------------------- KeyError Traceback (most recent call last) Input In [13], in <cell line: 2>() 1 info.pop("employer") # fired for tormenting Science students ----> 2 print(info["employer"]) KeyError: 'employer'
def distribution(lst: typing.Sequence) -> dict[typing.Any, int]:
r = {}
for val in lst:
if not (val in r):
r[val] = 0
r[val] = r[val] + 1
return r
print(distribution([
8, 6, 7, 5, 3, 0, 9, 2, 4, 6, 0, 1
]))
{8: 1, 6: 2, 7: 1, 5: 1, 3: 1, 0: 2, 9: 1, 2: 1, 4: 1, 1: 1}
def distributionChart(lst: typing.Sequence) -> None:
dist = distribution(lst)
for key in sorted(dist):
print(key, "*" * dist[key])
distributionChart([
8, 6, 7, 5, 3, 0, 9, 2, 4, 6, 0, 1
])
distributionChart("Antidisestablishmentarianism is a long word, but not as long as pneumonoultramicroscopicsilicovolcanoconiosis!")
0 ** 1 * 2 * 3 * 4 * 5 * 6 ** 7 * 8 * 9 * ********** ! * , * A * a ******** b ** c ****** d ** e *** g ** h * i ************ l ****** m **** n ********** o ************* p ** r **** s *********** t ****** u *** v * w *
annoying = {}
annoying[0.3-0.2] = "Hello"
annoying[0.1] = "world"
print(annoying)
{0.09999999999999998: 'Hello', 0.1: 'world'}
def first(s: str) -> str:
print(s, "->", s[0])
return s[0]
print(sorted(
["an", "aardvark", "ate", "ants"],
key=first
))
an -> a aardvark -> a ate -> a ants -> a ['an', 'aardvark', 'ate', 'ants']
def toDictionary(seq: typing.Sequence) -> dict:
r = {}
for idx in range(len(seq)):
r[idx] = seq[idx]
return r
print(toDictionary("Hello, world!"))
{0: 'H', 1: 'e', 2: 'l', 3: 'l', 4: 'o', 5: ',', 6: ' ', 7: 'w', 8: 'o', 9: 'r', 10: 'l', 11: 'd', 12: '!'}
import time
memo: dict[tuple[int, int], list[int]] = {}
def divisors(x: int, y: int) -> list[int]:
if (x, y) in memo:
return memo[(x, y)][:]
r = []
i = 1
while i <= x and y <= y:
if x%i == 0 and y%i == 0:
r.append(i)
i = i + 1
memo[(x, y)] = r
return r[:]
a = time.time()
divisors(44100, 48000)
b = time.time()
divisors(44100, 48000)
c = time.time()
print("First time took", b-a)
print("Second time took", c-b)
print(divisors(44100, 48000))
divisors(44100, 48000).append("a bag full of squirrels")
print(divisors(44100, 48000))
<cell>28: error: Argument 1 to "append" of "list" has incompatible type "str"; expected "int" [arg-type]
First time took 0.006996870040893555 Second time took 6.437301635742188e-05 [1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 25, 30, 50, 60, 75, 100, 150, 300] [1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 25, 30, 50, 60, 75, 100, 150, 300]
import random
def bins(min: float, max: float, binCt: int) -> list[tuple[float, float]]:
bins = []
span = max - min
for binNum in range(binCt):
bins.append((
span/binCt*binNum + min,
span/binCt*(binNum+1) + min
))
return bins
rands = []
for _ in range(1000):
rands.append(random.random() ** 2)
randsSorted = sorted(rands)
print(bins(randsSorted[0], randsSorted[-1], 10))
[(8.022268725054259e-09, 0.09977046979624656), (0.09977046979624656, 0.1995409315702244), (0.1995409315702244, 0.2993113933442022), (0.2993113933442022, 0.39908185511818006), (0.39908185511818006, 0.4988523168921579), (0.4988523168921579, 0.5986227786661357), (0.5986227786661357, 0.6983932404401135), (0.6983932404401135, 0.7981637022140914), (0.7981637022140914, 0.8979341639880692), (0.8979341639880692, 0.9977046257620471)]
def findBin(val: float, bins: list[tuple[float, float]]) -> tuple[float, float]:
# Fix the exclusivity problem
if val <= bins[0][0]:
return bins[0]
if val >= bins[-1][1]:
return bins[-1]
# Look for a matching bin
for bin in bins:
if val >= bin[0] and val < bin[1]:
return bin
return bins[-1]
print(findBin(
0.5,
bins(randsSorted[0], randsSorted[-1], 10)
))
print(findBin(
7,
bins(randsSorted[0], randsSorted[-1], 10)
))
print(findBin(
-7,
bins(randsSorted[0], randsSorted[-1], 10)
))
(0.4988523168921579, 0.5986227786661357) (0.8979341639880692, 0.9977046257620471) (8.022268725054259e-09, 0.09977046979624656)
def histogram(values: list[float], binCt: int) -> dict[tuple[float, float], int]:
s = sorted(values)
vBins = bins(s[0], s[-1], binCt)
r = {}
# Each bin starts empty
for bin in vBins:
r[bin] = 0
# Add the values
for val in values:
bin = findBin(val, vBins)
r[bin] = r[bin] + 1
return r
print(histogram(rands, 10))
{(8.022268725054259e-09, 0.09977046979624656): 295, (0.09977046979624656, 0.1995409315702244): 147, (0.1995409315702244, 0.2993113933442022): 95, (0.2993113933442022, 0.39908185511818006): 85, (0.39908185511818006, 0.4988523168921579): 81, (0.4988523168921579, 0.5986227786661357): 58, (0.5986227786661357, 0.6983932404401135): 62, (0.6983932404401135, 0.7981637022140914): 53, (0.7981637022140914, 0.8979341639880692): 53, (0.8979341639880692, 0.9977046257620471): 71}
def histogramChart(lst: list[float], binCt: int) -> None:
hist = histogram(lst, binCt)
for key in sorted(hist):
print(key, "*" * hist[key])
histogramChart(rands, 10)
(8.022268725054259e-09, 0.09977046979624656) ******************************************************************************************************************************************************************************************************************************************************************************************************* (0.09977046979624656, 0.1995409315702244) *************************************************************************************************************************************************** (0.1995409315702244, 0.2993113933442022) *********************************************************************************************** (0.2993113933442022, 0.39908185511818006) ************************************************************************************* (0.39908185511818006, 0.4988523168921579) ********************************************************************************* (0.4988523168921579, 0.5986227786661357) ********************************************************** (0.5986227786661357, 0.6983932404401135) ************************************************************** (0.6983932404401135, 0.7981637022140914) ***************************************************** (0.7981637022140914, 0.8979341639880692) ***************************************************** (0.8979341639880692, 0.9977046257620471) ***********************************************************************