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 f(n):
if (n < 0):
n = -n
if (n == 0):
return 0
else:
return n%10 + f(n//100)
def ct1A():
print('ct1A:')
print(f(8))
print(f(123))
print(f(-150112))
ct1A()
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 ct2A(n):
if (n == 0):
return 'x'
elif (n == 1):
return 'y'
else:
return ct2A(n//2) + str(n) + ct2A(n//3)
print(ct2A(8))
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 g(n):
# this is a helper function for rc1
if (n == 0):
return 0
x = n % 10
if (x // 4 == 2):
return 1 + g(n//10)
elif (x % 2 == 0):
return 'a'
else:
return g(n//10)
def rc1A(n):
return (n > 12345) and (g(n) == 3)
4. Free Response: evenRangeSum [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 evenRangeSum(lo, hi)
which takes two integers and returns the
sum of just the even numbers in the range, inclusive.
So for instance, rangeSum(2,6)
should return 12 (because 2+4+6 == 12).
Note that rangeSum(6, 2) returns 0 since there are no numbers in that range.
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, 5) for x in range(5)])
print(f(3, 4))