Skip to main content

Module 3 · before

Algorithms

6 questions on what this module teaches. Guessing is fine: this is your starting point, not a test. Take the same check again at the end to see what you learned.

1. What does this print?
def flip(items):
    if len(items) == 0:
        return []
    return flip(items[1:]) + [items[0]]

print(flip([1, 2, 3]))
2. What does this print?
needs = {'a': ['b', 'c'], 'b': ['d'], 'c': ['d', 'e'], 'd': [], 'e': []}

def explore(item, visited, order):
    if item in visited:
        return
    visited.add(item)
    order.append(item)
    for before in needs[item]:
        explore(before, visited, order)

order = []
explore('a', set(), order)
print(order)
3. What does this print?
needs = {'cake': ['batter', 'oven'], 'batter': ['eggs', 'flour'],
         'oven': [], 'eggs': [], 'flour': []}

def topo_order(goal):
    order = []
    visited = set()
    def build(item):
        if item not in visited:
            visited.add(item)
            for before in needs[item]:
                build(before)
            order.append(item)
    build(goal)
    return order

print(topo_order('cake'))
4. Your name generator gives different names every time you run it, and you want every run to give the same names. Where should random.seed(42) go?
5. random.choices(['a', 'b', 'c'], weights=[2, 1, 1], k=1000) rolls a die 1,000 times. About how many rolls are 'a'?
6. What does this print?
def multiplications(rows, cols):
    count = 0
    for r in range(rows):
        count += cols
    return count

print(multiplications(8, 4) + multiplications(4, 8))

Your answers are saved with a random id, not your name, so we can see which lessons work. Privacy