CS代写 | Structure and Interpretation of Computer Programs CS 61A

Preliminaries

You can complete and submit these questions before the exam starts.

(a) What is your full name?

(b) What is your student ID number?

1. (6.0 points) The Droids You’re Looking For

Fill in each blank in the code example below so that executing it would generate the following environment
diagram on tutor.cs61a.org.

RESTRICTIONS. You must use all of the blanks. Each blank can only include one statement or expression.

def x(wing):

poe = lambda poe: _________

wing.append(_________)
# (b)

return _________
# (c)

droid = [8]

b = x([1])

_________
# (d)

(a) (1.0 pt) Which of these could ﬁll in blank (a)? Check all that apply.

wing + poe
wing.extend(poe)
wing.append(poe)
list(wing).extend(poe)
list(wing).append(poe)

(b) (1.0 pt) Fill in blank (b).

(c) (1.0 pt) Which of these could ﬁll in blank (c)?

poe(droid)
poe(wing)
poe(b)

(d) (3.0 pt) Fill in blank (d).

b([b([8])])

2. (16.0 points) Stoned

Deﬁnition: A hailstone sequence begins with a positive integer n. If n is even, divide it by 2. If n is odd, triple
it and add 1. Repeat until 1 is reached. For example, the hailstone sequence starting at 10 is 10, 5, 16, 8, 4, 2, 1.

Assume that all hailstone sequences are ﬁnite.

(a) (9.0 points)

Implement hailstone, which takes a positive integer n and a one-argument function g. It calls g on each
element of the hailstone sequence starting at n and returns the length of the sequence.

def hailstone(n, g):
“””Call g on each element of the hailstone sequence starting
at n and return its length.

>>> a = hailstone(10, print)
10
5
16
8
4
2
1
>>> a
7
>>> s = []
>>> hailstone(10, s.append)
7
>>> s
[10, 5, 16, 8, 4, 2, 1]
“””
if n == 1:

h = _________
# (a)

elif _________:
# (b)