In [4]:
def wordCount(s: str) -> int:
    """
    Returns the number of words in s.
    """
    #print("wordCount called with", s)
    return len(s.split())

def sortByWordCount(lst: list[str]) -> None:
    """
    Sorts lst by the number of words in each string, in place.
    """
    lst.sort(key=wordCount)
    
x = [
    "Oh what a world with such people in it",
    "a b c d e f g h i j k l m n o p q r s",
    "Hello, pneumonoultramicroscopicsilicovolcanoconiosis"
]

sortByWordCount(x)
print(x)
['Hello, pneumonoultramicroscopicsilicovolcanoconiosis', 'Oh what a world with such people in it', 'a b c d e f g h i j k l m n o p q r s']
In [5]:
info = (
    "Richards",
    "Gregor",
    1.76,
    "University of Waterloo",
    "Purdue University",
    2014,
    12
)

print(info[3])
University of Waterloo
In [6]:
info = {
    "surname": "Richards",
    "given name": "Gregor",
    "height": 1.76,
    "employer": "University of Waterloo",
    "alma mater": "Purdue University",
    "graduation year": 2014,
    "employment years": 12
}

print(
    info["given name"], info["surname"],
    "works at", info["employer"]
)
Gregor Richards works at University of Waterloo
In [7]:
info["employment years"] = info["employment years"] + 1
print(info["employment years"])
13
In [9]:
for x in info:
    print(x, info[x])
surname Richards
given name Gregor
height 1.76
employer University of Waterloo
alma mater Purdue University
graduation year 2014
employment years 13
In [10]:
print(list(info))
['surname', 'given name', 'height', 'employer', 'alma mater', 'graduation year', 'employment years']
In [11]:
print(info["citizenship"])
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
Input In [11], in <cell line: 1>()
----> 1 print(info["citizenship"])

KeyError: 'citizenship'
In [13]:
info["citizenship"] = ["USA"] # I can only apologize
print(info["citizenship"])
print(info["surname"])
['USA']
Richards
In [15]:
if "age" in info:
    print("This person is", info["age"], "years old")
In [16]:
info.pop("employer") # fired for tormenting Science students
print(info["employer"])
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
Input In [16], in <cell line: 2>()
      1 info.pop("employer") # fired for tormenting Science students
----> 2 print(info["employer"])

KeyError: 'employer'
In [18]:
import typing

def distribution(lst: typing.Sequence) -> dict[typing.Any, int]:
    """
    Returns the frequency distribution of values in lst as
    a dictionary associating the value with its count.
    """
    dist = {}
    for val in lst:
        # if val not in dist:
        if not (val in dist):
            dist[val] = 0
        dist[val] = dist[val] + 1
    return dist

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}
In [21]:
def distributionChart(lst: typing.Sequence) -> None:
    """
    Prints a distribution chart of the values in lst.
    """
    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])
0 **
1 *
2 *
3 *
4 *
5 *
6 **
7 *
8 *
9 *
In [22]:
distributionChart("oh what a world with such people in it")
  ********
a **
c *
d *
e **
h ****
i ***
l **
n *
o ***
p **
r *
s *
t ***
u *
w ***
In [23]:
annoying = {}
annoying[0.3-0.2] = "Hello"
annoying[0.1] = "world"
print(annoying)
{0.09999999999999998: 'Hello', 0.1: 'world'}
In [24]:
list("Hello, world!")
Out[24]:
['H', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd', '!']
In [25]:
dict([])
Out[25]:
{}
In [26]:
dict([1, 2, 3, 4, 5])
<cell>1: error: Argument 1 to "dict" has incompatible type "list[int]"; expected "Iterable[tuple[Never, Never]]"  [arg-type]
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Input In [26], in <cell line: 1>()
----> 1 dict([1, 2, 3, 4, 5])

TypeError: cannot convert dictionary update sequence element #0 to a sequence
In [27]:
dict([(0, 0), (1, 1), (2, 4), (3, 9)])
Out[27]:
{0: 0, 1: 1, 2: 4, 3: 9}
In [28]:
def toDictionary(seq: typing.Sequence) -> dict:
    """
    Returns seq converted to a dictionary.
    """
    r = {}
    for idx in range(len(seq)):
        r[idx] = seq[idx]
    return r

print(toDictionary([2, 4, 6, 0, 1]))
{0: 2, 1: 4, 2: 6, 3: 0, 4: 1}
In [29]:
def divisors(x: int, y: int) -> list[int]:
    """
    Returns the common divisors of x and y as a list.
    """
    r = []
    i = 1
    while i <= x and i <= y:
        if x%i == 0 and y%i == 0:
            r.append(i)
        i = i + 1
    return r

print(divisors(44100, 48000))
[1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 25, 30, 50, 60, 75, 100, 150, 300]
In [33]:
memo: dict[tuple[int, int], list[int]] = {}

def divisors(x: int, y: int) -> list[int]:
    """
    Returns the common divisors of x and y as a list.
    """
    # Check if it's memoized
    if (x, y) in memo:
        return memo[(x, y)]
    
    r = []
    i = 1
    while i <= x and i <= y:
        if x%i == 0 and y%i == 0:
            r.append(i)
        i = i + 1
        
    # Memoize the result
    memo[(x, y)] = r
    return r

print(divisors(44100, 48000))
print(divisors(44100, 48000))
[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]
In [34]:
import time

a = time.time()
divisors(48000, 44100)
b = time.time()
divisors(48000, 44100)
c = time.time()

print("First time", b-a)
print("Second time", c-b)
First time 0.004106760025024414
Second time 3.4809112548828125e-05
In [35]:
lst = divisors(2, 4)
lst.append("a bag full of squirrels")
<cell>2: error: Argument 1 to "append" of "list" has incompatible type "str"; expected "int"  [arg-type]
In [36]:
divisors(2, 4)
Out[36]:
[1, 2, 'a bag full of squirrels']
In [37]:
memo: dict[tuple[int, int], list[int]] = {}

def divisors(x: int, y: int) -> list[int]:
    """
    Returns the common divisors of x and y as a list.
    """
    # Check if it's memoized
    if (x, y) in memo:
        return memo[(x, y)][:]
    
    r = []
    i = 1
    while i <= x and i <= y:
        if x%i == 0 and y%i == 0:
            r.append(i)
        i = i + 1
        
    # Memoize the result
    memo[(x, y)] = r
    return r[:]

print(divisors(44100, 48000))
print(divisors(44100, 48000))
[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]