16-Generators 1pp
16-Generators 1pp
Announcements
Review: Iterables, Iterators
An iterable is any sequence we can iterate over (we can call iter() on it and get an iterator)
An iterator allows us to iterate over any iterable sequence (we can call next() on it and get
the next item in the sequence)
t = (1,2,3)
i = iter(t) other iterators:
next(i)
zip(), filter(), reversed()
l = ["John", "Jedi", "Shm"]
e = enumerate(l)
next(e)
d = {"apples": 1, "pears": 2}
m = map(lambda x: "yummy “ + x, d)
next(m)
Map Function Review
4 8 12 16
doubler
next(doubler)
5
Tree Practice
Spring 2023 Midterm 2 Question 4(a)
Implement exclude, which takes a tree t and a value x. It returns a tree containing the root
node of t as well as each non-root node of t with a label not equal to x. The parent of a
node in the result is its nearest ancestor node that is not excluded.
def exclude(t, x):
"""Return a tree with the non-root nodes of tree t labeled anything but x. 1
>>> t = plus_minus(3)
>>> next(t)
3
>>> next(t)
-3
>>> t
<generator object plus_minus ...>
(Demo)
9
Spring 2023 Midterm 2 Question 5(b)
Definition. When parking vehicles in a row, a motorcycle takes up 1 parking spot and a car
takes up 2 adjacent parking spots. A string of length n can represent n adjacent parking
spots using % for a motorcycle, <> for a car, and . for an empty spot.
For example: '.%%.<><>' (Thanks to the Berkeley Math Circle for introducing this question.)
Implement park, a generator function that yields all the ways, represented as strings, that
vehicles can be parked in n adjacent parking spots for positive integer n.
def park(n):
"""Yield the ways to park cars and motorcycles in n adjacent spots.
>>> sorted(park(1))
['%', '.']
>>> sorted(park(2))
['%%', '%.', '.%', '..', '<>']
>>> len(list(park(4))) # some examples: '<><>', '.%%.', '%<>%', '%.<>'
29
"""
10
Fibonacci Generator
def fib_generator():
"""
A generator that yields the Fibonacci sequence indefinitely.
(The Fibonacci sequence starts with 0 and 1, and each subsequent number
is the sum of the previous two.)