CMU 15-110: Principles of Computing
Week11 Practice (Due never)
Contents:
1. Code Tracing
What will this code print? Figure it out by hand, then run the code to confirm. Then slightly edit the code and try again.
- Trace #1:
def ct1(n): if (n == 0): return False elif (n%2 == 1): return True else: return ct1(n//10) print(ct1(2684)) print(ct1(2674)) # What in general does ct1(n) compute?
- Trace #2:
def ct2(L): # assume L is at least of lenght 1 if (len(L) == 1): return L[0] else: first = L[0] rest = L[1:] m = ct2(rest) if (m < first): return first else: return m print(ct2([5,2,6,7,3,4])) # What in general does ct2(L) compute?
- Trace #3:
def ct3(n): if (n < 10): return n else: ones = n%10 rest = n//10 if (ones > 0): return 10*ct3(rest) + ones else: return ct3(rest) print(ct3(102)) print(ct3(104023)) # What in general does ct3(n) compute?
- Trace #4:
def ct4(L): if (len(L) < 2): return L*2 else: return [L[0]] + ct4(L[1:]) + [L[0]] print(ct4([1,2,3])) # What in general does ct4(L) compute?