[go: up one dir, main page]

0% found this document useful (0 votes)
11 views11 pages

16-Generators 1pp

Uploaded by

gwen43
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views11 pages

16-Generators 1pp

Uploaded by

gwen43
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Generators

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

map(func, iterable) applies a given function to each item of an iterable

4 8 12 16

doubler

next(doubler)

l = [2, 4, 6, 8] def double(x):


print(f"*** doubling {x} ***")
doubler = map(double, l) return x*2
map() Practice

def add_to_each(p, edit):


"""
Given a list, p, of 3-element tuples: [(x1, y1, z1), (x2, y2, z2), ...]
And an edit tuple (also 3 elements) = (a, b, c),
return a map object where
a is added to each x-value,
b to each y-value, and
c to each z-value.

>>> list(add_to_each([(0, 0, 0), (1, 1, 1)], (10, 10, 10)))


[(10, 10, 10), (11, 11, 11)]
>>> list(add_to_each([(1, 2, 3), (1, 1, 1)], (10, 20, 30)))
[(11, 22, 33), (11, 21, 31)]
“""
return map(lambda x: ( x[0] + edit[0], x[1] + edit[1], x[2] + edit[2] ), p)

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 = tree(1, [tree(2, [tree(2), tree(3), tree(4)]), tree(5, [tree(1)])]) 2 5


>>> exclude(t, 2)
[1, [3], [4], [5, [1]]] 2 3 4 1
>>> exclude(t, 1) # The root node cannot be excluded
[1, [2, [2], [3], [4]], [5]]
""" 2 5
exclude(y, x)
filtered_branches = map(lambda y: _______________, branches(t))
bs = [] 2 3 4 1
for b in filtered_branches: In Spring 2023,
37% of students
20% of students
label(b) == x got this right 1
30% got if ________________: got this right
it right;
extend branches(b)
bs.________(______________) 24% got 2 5
1 of 4
options else: it right
bs.append(b) 2 3 4 1
return tree(label(t), bs)
7
Generators
Generators and Generator Functions

>>> def plus_minus(x):


... yield x
... yield -x

>>> t = plus_minus(3)
>>> next(t)
3
>>> next(t)
-3
>>> t
<generator object plus_minus ...>

A generator function is a function that yields values instead of returning them


A normal function returns once; a generator function can yield multiple times
A generator is an iterator created automatically by calling a generator function
When a generator function is called, it returns a generator that iterates over its yields

(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.)

>>> fib = fib_generator()


>>> next(fib)
0
>>> next(fib)
1
>>> next(fib)
1
>>> next(fib)
2
>>> list(next(fib) for i in range(0,10)) # list the next 10 fibonacci numbers
[3, 5, 8, 13, 21, 34, 55, 89, 144, 233]
"""
a, b = 0, 1
while True:
yield a # Yield the current Fibonacci number
a, bb == b,
a, b, aa ++ bb # Prepare the next Fibonacci numbers
11

You might also like