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 g(n):
if (n < 0):
n = -n
if (n == 0):
return 0
else:
a = n%100
b = g(n//10)
if (a > b):
return a
else:
return b
def ct1B():
print('ct1B:')
print(g(8))
print(g(15112))
print(g(-67234))
ct1B()
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 ct2B(s):
if (s.startswith('c')):
return 'X'
elif len(s) < 2:
return s + 'Y'
else:
return ct2B(s[:-1]) + s[0] + ct2B(s[1:])
print(ct2B('abc'))
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 f(n):
# this is a helper function for rc1
if (n == 0):
return 0
x = n % 10
if (x % 5 == 2):
return 1 + f(n//10)
elif (x < 6):
return 'a'
else:
return f(n//10)
def rc1B(n):
return (n > 12345) and (f(n) == 3)
4. Free Response: tripleFib [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: s[1:], s[:-1], s[1:-1]
But these are not ok: s[::-1], s[::2],...
With this in mind, write the function
tripleFib(n) which returns the nth value of the
tripleFibonacci sequence. This is like the normal Fibonacci sequence, but each
value is the sum of the
three values before it.
Also, note that the first thee values are all 1's.
Thus, the sequence is 1, 1, 1, 3, 5, 9, 17, ... and so on.
Note: If n is negative, tripleFib(n) should return 0.
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 * d
else:
m[x] = (f(x-1, d) + f(x-2, d)) * d
return m[x]
print([f(x, 2) for x in range(5)])
print(f(3, 4))