CS 61A Structure and Interpretation of Computer Programs Summer 2018
CS 61A Structure and Interpretation of Computer Programs Summer 2018
INSTRUCTIONS
Student ID Number
Berkeley Email
• You may use built-in Python functions that do not require import, such as min, max, pow, and abs.
• For fill-in-the blank coding problems, we will only grade work written in the provided blanks. You may only
write one Python statement per blank line, and it must be indented to the level that the blank is indented.
• Unless otherwise specified, you are allowed to reference functions defined in previous parts of the same question.
2
• If an error occurs, write Error, but include all output displayed before the error.
• To display a function value, write Function.
• If an expression would take forever to evaluate, write Forever.
The interactive interpreter displays the value of a successfully evaluated expression, unless it is None.
Assume that you have started python3 (not ipython or other variants) and executed the code shown on the left
first, then you evaluate each expression on the right in the order shown. Expressions evaluated by the interpreter
have a cumulative effect.
• Add all missing names and parent annotations to all local frames.
• Add all missing values created or referenced during execution.
• Show the return value for each local frame.
Global frame
pet "dog"
bug 3
f1: [parent: ]
Return Value
f2: [parent: ]
Return Value
f3: [parent: ]
1 pet = "dog"
2 bug = 3
3
Return Value 4 def to(do):
5 bug = 5
f4: [parent: ] 6 if do == "sleep":
7 return "zzz"
8 return lambda bye: bye - bug
9
10 def walk(time):
Return Value 11 pet = "cat"
12 bed = time()
f5: [parent: ] 13 if not bed(bug):
14 return to("sleep")
15 else:
16 return (lambda: "itch")()
17
Return Value 18 walk(lambda: (to(pet) or not 2*pet))
4
(a) (2 pt)
1 a = [1, 2, 3]
2 b = [4, 5, 6] a
3 a.insert(a[0], b)
4 b.pop(a.pop(1))
b
(b) (2 pt)
1 c = [1, 2, 3]
2 d = [4, c, 6, 7] c
3 e = [d[x] for x in c]
4 d.append(e)
d
(c) (3 pt)
1 f, h = [1], [2]
2 f.extend([h, 3]) f
3 g = f[1:] + f[1:]
4 i = 0
5 while i < len(f): g
6 if i % 2 == 0:
7 h.append(g[f[i]])
8 i += 1 h
i
Name: 5
(a) (2 pt) A function is a higher order function if it has at least one of two particular properties. What are those
two properties?
1.
2.
(b) (2 pt) Give one reason why you shouldn’t violate abstraction barriers. Limit your answer to 15 words or less.
(c) (2 pt) What’s a difference between tuples and lists besides syntax? Limit your answer to 10 words or less.
(a) (4 pt) Write repeat_digits, which takes a positive integer n and returns another integer that is identical to
n but with each digit repeated.
def repeat_digits(n):
"""Given a positive integer N, returns a number with each digit repeated.
>>> repeat_digits(1234)
11223344
"""
last, rest = _____________________________________, _____________________________________
if ______________________________________________________________________________________:
return ______________________________________________________________________________
(b) (2 pt) Let d be the number of digits in n. What is the runtime of repeat_digits with respect to d?
√
# Θ(1) # Θ(log d) # Θ( d) # Θ(d) # Θ(d2 ) # Θ(2d )
6
The tree data abstraction is provided here for your reference. Do not violate the abstraction barrier!
def tree(label, branches=[]): def is_leaf(t);
return [label] + list(branches) return not branches(t)
def eight_path(t):
"""Returns a path of the labels from the root to a leaf whose sum is a multiple of eight,
or return None if no path exists.
t1 t2
>>> t1 = tree(5, [tree(2),
tree(1, [tree(3), 5 9
tree(2)]) 2 1
]) 5
>>> eight_path(t1) 3 2 2 1
[5, 1, 2]
>>> t2 = tree(9, [t1]) 3 2
>>> eight_path(t2)
[9, 5, 2]
"""
def helper(t, path_so_far):
_____________________________________________________________________________________
if __________________________________________________________________________________:
return path_so_far
for _________________________________________________________________________________:
result = ________________________________________________________________________
if result:
return ______________________________________________________________________
return __________________________________________________________________________________
Name: 7
Han and Lando are both very good at the game, so they play optimally. That is, if there is a move they can take
that will allow them to win (assuming their opponent also plays optimally), they will take it.
Write sabacc_winner, which takes a number of cards and two players, and returns the winner if both players play
optimally and player 0 goes first.
You must use recursion to solve this problem. Writing the closed-form solution will receive no credit.
if ______________________________________________________________________________________:
return player0
if ______________________________________________________________________________________:
return player1
__________________ = ____________________________________________________________________
__________________ = ____________________________________________________________________
if ______________________________________________________________________________________:
return player0
return player1
8
As an example, here’s a simple messenger function that returns a sentence with all of the words that have been
provided.
>>> simple_messenger("Avengers")("assemble")(".")
'Avengers assemble.'
>>> simple_messenger("Get")("this")("man")("a")("shield")(".")
'Get this man a shield.'
Write thanos_messenger, which is a messenger function that discards every other word that’s provided. The first
word should be included in the final sentence, the second word should be discarded, and so on.
def thanos_messenger(word):
"""A messenger function that discards every other word.
>>> thanos_messenger("I")("don't")("feel")("so")("good")(".")
'I feel good.'
>>> thanos_messenger("Thanos")("always")("kills")("half")(".")
'Thanos kills.'
"""
assert word != '.', 'No words provided!'
def new_messenger(word):
if word == '.':
return ______________________________________________________________________
if ______________________________________________________________________________:
return ______________________________________________________________________
return __________________________________________________________________________
return ______________________________________________________________________________
return __________________________________________________________________________________
Name: 9
• Mark the choice to “Betray” and write a positive integer in the blank below. The one student who writes the
smallest, unique positive integer will receive two (2) extra credit points but only if fewer than 90% of students
choose the next option.
• Mark the choice to “Work Together”. If at least 90% of students choose this option, all students who chose this
option will receive one (1) extra credit point and those who marked the choice to “Betray” will receive zero (0)
extra credit points.
Will you work together ? Or will you betray your fellow students? It is up to you.
# Betray
# Work Together
(a) (0 pt) Implement lcs, which finds the length of the longest common subsequence between two words. Note
that the ordering of the characters must be preserved.
if ______________________________________________________________________________________:
return ______________________________________________________________________________
elif ____________________________________________________________________________________:
return ______________________________________________________________________________
return __________________________________________________________________________________
(b) (0 pt) What is the runtime (in the worst case) of lcs? By worst case, we mean we want you to consider inputs
that would be particularly time consuming for lcs.
10
(c) (0 pt) Now, implement lcs_fast which does the same thing as lcs, but has a time complexity of Θ(m ∗ n),
where m is the number of characters in word1 and n is the number of characters in word2.
def lcs_fast(word1, word2):
(d) (0 pt) Provide a high-level proof as to why the runtime of your implementation of lcs_fast is Θ(m ∗ n).
(a) (0 pt) Can you name the movie coming out / already released this summer that each problem title is referencing?
1. 5. 9.
2. 6. 10.
3. 7. 11.
4. 8.
(b) (0 pt) Any feedback for us on how this exam went / how the course is going so far?