1. Code Tracing 1 [20 points]
What does the following code print?
Be certain to show your work,
and also very clearly circle your answer!
def h(s, c):
if (s == ''):
return 0
else:
a = h(s[1:], c)
if (s[0] == c):
b = 1
elif (str(a * 2) == c):
b = 10
else:
b = 0
return a + b
def ct1C():
print('ct1C:')
print(h('1234','3'))
print(h('927262', '2'))
print(h('124222', '2'))
ct1C()
2. Code Tracing 2 [20 points]
What does the following code print?
Be certain to show your work,
and also very clearly circle your answer!
def ct2C(n):
if (n == 0):
return 'x'
elif (n == 1):
return 'y'
else:
return ct2C(n//4) + str(n) + ct2C(n//2)
print(ct2C(9))
3. Reasoning Over Code [10 points]
What input makes the following function return True?
Be certain to show your work,
and also very clearly circle your answer!
def h(n):
# this is a helper function for rc1
if (n == 0):
return 0
x = n % 10
if (x % 2 == 0):
return 1 + h(n//10)
else:
return h(n//10)
def rc1C(n):
return ((n > 12345) and
(h(n) == 3) and
(h(n//100) == 2))
4. Free Response: makePal [50 points]
Note: you may not use helper functions, wrapper functions,
default parameters, etc. You must write a single recursive function
to solve each of these.
Also: you may not use ANY builtin functions at all. So you cannot use
abs, len, max, min, pow, count, ...
Also: no slicing allowed except when you are excluding just a small constant
number of values, such as excluding just the first value,
excluding just the last value, or excluding both of those.
So these are all ok: L[1:], L[:-1], L[1:-1]
But these are not ok: L[::-1], L[::2],...
You also may not use list methods like .pop() or .insert()
With this in mind, write the function
makePal(L) which takes a list of integers L, and returns a new
list of integers M of twice the original length. If N is the length
of L, then the first N values in M are the same as in L, and the last
N values in M are those values in reverse.
For example, if L = [1,2,3], then makePal(L) returns [1,2,3,3,2,1].
5. Bonus/Optional: Code Tracing [2.5 points]
What does the following code print?
Be certain to show your work,
and also very clearly circle your answer!
def f(x, d, m={ }):
# hint: { } is mutable
if (x not in m):
if (x < 2):
m[x] = 1
else:
m[x] = f(x-1, d) + (f(x-2, d) * d)
return m[x]
print([f(x, 3) for x in range(5)])
print(f(3, 4))