CS 61A Structure and Interpretation of Computer Programs
Fall 2020 Quiz 7
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. Node Function Generator
(a) Construct the generator function node_func_gen, which takes in a tree t, a one-argument filter function
f and a one-argument mapping function g. node_func_gen yields one positional node function for each
node position in the t. A positional node function takes in a tree as an argument and returns the value
of the node at the specified position. For example, a positional node function constructed for the root of
a tree will return the label of the root of any tree that it is given. You may assume that any trees passed
to your positional functions have the same structure as t.
You may not use list or any sort of comprehension.
def node_func_gen(t, f, g):
���
>>> f = lambda x: x % 2 == 1
>>> g = lambda x: x**2
>>> for func in node_func_gen(t1, f, g) # note: order doesn�t matter
… print(func(t1))
…
1
25
9
49
���
if ___________________________________________________________________________:
yield ____________________________________________________________________
for i in range(len(t.branches)):
yield from __________(____________________________________________________, \
____________________________________________________)
t
so
f t 4
lambda f lambdat f Ebranches i
f f label
lambda x g Xlabel
map lambda i lambdaf i Lambda t f EbranchesEf
function nodeforegenCtbranchesfit f giterable
Pgp
lambda0 lambda f lambda6 f fbranchesfi i
Basecase
Whendoyouyieldavalve Say fonlykeeps evenvalues
do yieldI doweyield2here
Oncewedecidetoyieldavalve
howshouldwemodifyit
use
g
if f Elabel
yieldgCt
label
Howaboutintherecursivecase
Whatdowegetwhenwerecuseon abranch LeapofFaith1
wegetageneratoroffunctionswhichtakeus
fromthatchildnodeto ourfilteredmapped nodevalues
d
Allwe havetodoismodifythesefunctionssotheytakeyoufromthe roottothechildthenrecursionwilltakeyoutherest
theway
g
sowe wantto mapthismodicationontoallrecursivelyyielded
functions
Iso d
functionfam
recursion
k 2to4
map nodefmcgen E
branchesEl fg
i
shouldtakein a function f andreturna positionalnodefunction
fromrootof t totarget
needstomapEtoithbranchfrost
Cambda i lambda f lambdaE fCtbranches i3 o
3
2. Fibonacci Tree
Implement fib_tree, which takes in a non-negative integer n and returns a depth-n Fibonacci tree of depth n.
The root label of a depth-n Fibonacci tree is the nth Fibonnaci number (indexed from zero), and each node in
the tree has exactly two children which contain the values needed to compute the Fibonacci number of their
parent. If no lower Fibonacci numbers are required to compute the value of a node, then the node is a leaf.
def fib_tree(n):
���
>>> t = fib_tree(6)
>>> t.label
8
>>> t.branches[0].label
5
>>> t.branches[1].label
3
���
if _______________________________________________________________________
return _______________________________________________________________
bs = _____________________________________________________________________
return __________________________________________________________________
fibutreecz
bs fis treeCD f tco
I
In 2 1
Treeln too
fibfreeCnD Ab treeln27
TreeCbsLOLlabeltbs B label bs
i fibtreecy
o
no
no
4
3. Subsequence Generator
(a) Implement subsequences, which takes in a list lst and yields all subsequences of lst. You may not use
the list function or any comprehensions.
def subsequences(lst):
���
>>> for seq in subsequences([1, 2, 3]) # note: order doesn�t matter
… print(seq)
…
[1, 2, 3]
[1, 2]
[1, 3]
[1]
[2, 3]
[2]
[3]
[]
���
if __________________________________________-:
yield from map(___________________________________, __________________________)
yield from ___________________________________________________________________
else:
yield ________________________________________________________________________
yield
from x foritemin
yieldhomy yielditem
for itemin y
yielditem
modifyresultstoincludetaxbeginning
D
Cased includefirstitea
Casey don’t
includefirstiten
don’tneedtomodify
recursiveresults
puts 1st
Cotontothefrontofall
results
1st a
oosel lambdaseq Ust seq subsequences ClD
cash subsequences Std3
C
discards1st
i subsequences 1,23
weknow 1st D up 2,3I
CB toadd O fdoitadrgy.aadsubseueaceqffgEDqzz.gg
tf lo f a
Glo Glo
subsequences CT
5
4. Minimax
You are playing a game with a friend. At the end of the game you are both given the same score. Your friend
wants to make this score as low as possible, and you want to make this score as high as possible. This situation
can be modeled with a tree: leaf nodes correspond to the game being over and contain the score at the end of
the round. The values of intermediate nodes don’t matter.
Both you and your friend have perfect knowledge of this game tree t. With this setup, implement first_move,
which takes in a game tree t as input and outputs the index of the branch in the tree corresponding to your
optimal first move.
Hint: all even-depth layers correspond to your turns, and all odd-depth layers correspond to your friend’s
turns.
def first_move(t):
���
>>> first_move(t1)
2
>>> # best choice is the rightmost child (value is 7)
>>> # index of rightmost child in t.branches is 2
���
def optim_val(tr, fn=____________________):
if tr.is_leaf():
return __________________________
return ____________([____________________________________________________________])
return max(_____________________________, key=______________________________________)
Min
Max or min probably
triabel
fn OptionVal b miniffnismaxelsemax forbintrbranches
rangellen Ebranches lambda i optionvalltbranches
O
130 defmaxuscoreCES
bQ returnt.labelift.isleaf
elsemaxcaakscorelb for
biathranches