WELCOMETO EXAMPREP5
notsponsored
We’llstartat Berkeleytome 2 10pacifictime
WorksheetcanbefoundintheDrivefolder linkscsbla.orgexamprep
MusicDjangoReinhardt
MinorSwing Beyondthseea
Brazil
Feelfreeto ask questions in themeantime
CS 61A Structure and Interpretation of Computer Programs Fall 2020 Quiz 5
INSTRUCTIONS
• Please review this worksheet before the exam prep session. Coming prepared will help greatly, as the TA will be live solving without allocating much time for individual work.
• Either Sean or Derek will be on video live solving these questions. The other TA will be answering questions in the chat. It is in your best interest to come prepared with specific questions.
• This is not graded, and you do not need to turn this in to anyone. Below is a tree, which will be referred to as t1 in future questions.
2
1. Tree Printer
(a) Your friend wants to print out all of the values in some trees. Based on your experience in CS 61A, you decide to come up with an unnecessarily complicated solution. You will provide them with a function which takes in a tree and returns a node-printing function. When you call a node-printing function, it prints out the label of one node in the tree. Each time you call the function it will print the label of a different node. You may assume that your friend is polite and will not call your function after printing out all of the tree’s node labels. You may print the labels in any order, so long as you print the label of each one exactly once.
def node_printer(t):
>>> t1 = tree(1, [tree(2,
[tree(5),
tree(6, [tree(8)])]),
…
…
…
…
>>>
>>> printer()
1
tree(3),
… 3
26 8
printer()
tree(4, [tree(7)])])
printer = node_printer(t1)
lamb
>>> printer()
4
>>> printer()
7
>>> for _ in range(5):
lambda
nexnt ode lamb l
print
def step():
nonlocal lamb
to
E
reassignedto area afunction thatcontains
visit
I
5
lamb = __l_a__m__b__d__a_________________________________________________________________
ft
next_node, lamb = lamb()
print(_________________________________________________________________________)
label next node
for ____________________________________________________________________________
b in branchesnextnode _______________________________________________________________l_a_m___b________
lamb lambda x f lambda X f b return step afford btolamb
lamb
lambda b lamb
lamb
lamb lanbd.x.fianbdCa x.fSl
Notes
lamb is a function
on
Ittakes noinputs Itsfirstoutpuits probably anode
I t s s e c o n d o u t p u t i s a n o t h e r f u n c t i o no f t h e s a m es t r u c t u r e
each C callwe should exactly onething step print
whadt owehaveaccessto
land afunction hardtounderstand
sothe returnfrom should first land be
print labelnextnode
w h a t i f w e ‘ r ep r i n t i n gn o d e sf a r t h e rd o w n a new uniquenode
t
a t r e e b u to n l yp o i n t s t o t h e r o o f next Seemspromising
n.de
weneedtoprogressthrougthhe wholetree Howdowedecidewheretogonext
I thiwsould usrepeats tisthe
can’tuse because give rootnode nexntode
becauseit printed c
weneedtoconsiderall of nextnode’schildren wewon’vt isit d
again
onlygets on
for bin branches nextnode Now whatdowedoforeachofthesebranches
Wecan’rtecorse immediately weneedto send to visitlater d nodeseachtime Fromlambs
wheredoweget if lambwere
Howmightwedothis tE
nexIto Eovisit de pop
for bin branchesnexnt ode toVisitappendb
nt with Let’simplemey
y
you’ll
m a y n e
t o v i s i t
s e l e c t a n e wn o d ae n d removeit fromlist ofnodetsovisit
functions lambda
Inetssercea list
linked which learnaboultater
FIFA
Sof wanttocreate anewlambdafunctionwhichreturns y o u n e w v a l u ea n d t h e p r e v i o u s l a m b d a f u n c t i o n
your
forbin branchesnextnode
thisinfoinlocalvariables store
a list
this
Ournextnode tovisiptopalineisreplacedwithnextnodelamb lambC
Howdowe append tothislambdafunction
t o t h en e x t
inanefuture
function functions reference lambda
n e s t e dl a m b d a e a c oh n eh o l d s o n ve a l u ae n d a Storein
lambdaCx f
initialize contain root treeandits
b lamb
F i n a l l y h o wd o w e l a m b I t s h o u l d t h e n o d oe f t h e s e c o n rde t u r nv a l u e
lamb lambda x f
doesn’tmattesrince itwilnlevebr ecalledSoonexampleconebe lamb Lambda Ct None
2. Layer Generator
(a) Construct the generator function layer_gen, which takes in a tree t and returns a layer iterator of t. A layer iterator returns label values of nodes in the tree in level order; that is, it yields the root node, then each node from the second level, then each node from the third level and so on. Hint: consider using the pop method of lists.
def layer_gen(t):
>> lg = layer_gen(t1)
>>> for node_label in lg:
… print(nodel_label)
1
2
3
4
5
6
7
8
3
Ef
to visit
while _____________________________________________________________:
___________________________________________________________________
to
visit
to visit o pop
node = ________________________________________________________
labelnode
_______________________________________________________________
print
_____________e_x__t_e_n__d___b_r_a__n_c__h_e__s______________________________ to visit node
4
3. Fibonacci Generator
(a) Construct the generator function fib_gen, which returns elements of the Fibonacci sequence in order.
Hint: The solution doesn’t require any lambda functions or crazy workarounds, but instead a clever leap of faith. Consider using the zip function.
def fib_gen():
>>> fg = fib_gen()
>>> for _ in range(10):
… print(next(fg))
0
1
1
2
3
5
8
13
21
34
a
0
yield from ___________I__________________________________________________
fibgeno ________________________________________________________________________
a = ____________________________________________________________________
nextta
x y in ZipcarfibgenCD ____________________________________________________________________
for ____________________________________________________________________:
yield Xty forb gen
gives
rexts D OcI2
3S
8
0I12 About
35 8
What shouldweyieldfromtostart
Remembetr hetwo basecasesofFibonacci fcos 0 FCD I
yieldfrom O D
Wedon’thavenoughlinestokeeptrackof preandconandtoyieldvalues
solet’srecorse
1 have and farbutthat’senoughtocreattehenext
www.fib.gencan o u t p u st of a r
of
W eo n l y 0
can’treachbackto previousvalvessoinstead letsgetwo
O1 newinstance
offsetby I C
So we
needtocreatetwoFbgenerators
onethathasteppedforward 1 by
I s o valueinthesequence
Butwe get Fibonaccisequences sidebyside
just their at andyield sumeach
step
t o m o v ea n i t e r a t o f r o r w a r d w ec a l l n e x t
So a fibgenC nexta y
forX inZipafibgenGi yieldXty
4. Partition Generator
(a) Construct the generator function partition_gen, which takes in a number n and returns a n-partition iterator. An n-partition iterator yields partitions of n, where a partition of n is a list of integers whose sum is n. The iterator should only return unique partitions; the order of numbers within a partition and the order in which the partitions are returned does not matter.
partitions all
I
yieldhelper 2,2 It yieldhelped
forvalveinx yieldvalue
from
def partition_gen(n):
yield
>>> for partition in partition_gen(4): # note: order doesn t matter
… print(partition)
[4]
[3, 1]
2
to
2 CES
i Few.heipercer
[2, 2]
[2, 1, 1]
[1, 1, 1, 1]
useusek caseddon’t
large.SI uswehYohfafition
wewanttorotition
Sj def yield_helper(j, k):
ofsize if ______________________________________________________________________________:
Ek jo elements C
Ift
4 yield.hu
Cate
K
Cli
i
yield _______________________________________________________________________
elif ____________________________________________________________________________:
K
0
O and j
for _________________________________________________________________________:
Smallpart in yield helper j k k
yield ___________________________________________________________________
k t smallpart
yield _f_r__o__m____________h_e__l_p_e__r_c_j____________________________________________
Kl
yield _f__r_o__m_________________________________________________________________________
yield
T yieldhelperCn n
remembetrhe Fron
d yiednecpercc.cl
5
Similartocourptartitions forwhat andkrepresent cangivea goodhigpothesis j
let Ethecurrent numberwe’re to Mayte j trying partition
could alsousete
kEthelargestnumberwe’reallowedtopartitionwith to
smallest
yield fromyield helpelra n
W h y c a n ‘ t w ej u s t r e c o r s e o n y i e l d p a r t i t i o n s
ideaSaywehave n 6 Thenyieldalluniquepartitionos f5andputifathend
1 Problems
BASECASES
s i m i l at ro c oj u npt a r t i t i o n s
o thenthereisekactyoneparlition
if
all uniquepartitionsof4maps 23atmend andsoon
Doesn’t guaranteeuniqueness
palliationof5socould 2 I I I l 2 I I l isa valid get
1 1 1 i t l i s a v a l i d p a r t i t i o no f 4 s oc o u l dg e t 4 2
samepartition