CMU 15-112: Fundamentals of Programming and Computer Science
Extra Practice for Week 4 (Due never) Code Tracing (CT) and Reasoning Over Code (ROC) Exercises


This is part1! Also see extra-practice4-ct-and-roc-part2.html
These problems will help you prepare for hw4 and quiz4. They are optional and you are encouraged to collaborate when working on them.
Code Tracing (CT)
What will each of these print?

  1. Trace #1:
    def onesDigit(n): return n%10 def ct1(L): for i in range(len(L)): L[i] += sum(L) + max(L) return sorted(L, key=onesDigit) a = [2,1,0] print(ct1(a)) print(a)

  2. Trace #2:
    def ct2(a, b): a += [3] a = a + [4] for c in a: for i in range(len(b)): if (b[i] not in a): print("A", end="") b[i] += c elif (c % 2 == 1): print("B", end="") b += [c] elif (b[-1] != c): print("C", end="") b = b + [c] return (a,b) a = [4] b = [2,3] print(ct2(a,b)) print(a,b)

  3. Trace #3:
    def ct3(L): result = [ ] M = [L[i]*10**i for i in range(len(L))] for val in M: result.extend([val, L.pop()]) return result L = [2,5,3] M = ct3(L) print(L, M)

  4. Trace #4:
    def ct4(L): result = [ ] M = L[:] # same as M = copy.copy(L) if (M == L): result.append(1) if (M is L): result.append(2) if (M[0] == L[0]): result.append(3) if (M[0] is L[0]): result.append(4) return result print(ct4([5,7,6]))

  5. Trace #5:
    def ct5(L): M = L L += [4] M = M + [5] print(L, M) ct5(list(range(1)))

Reasoning Over Code (ROC)
Find values for the parameters so the functons return True:

  1. RC #1 of 2:
    def rc1(M): assert(isinstance(M, list) and (len(M) == 5)) for i in range(-1, 3): assert(M[i] == M[i-1] + i) return (sum(M) == 15)

  2. RC #2 of 2:
    def rc2(L): assert((isinstance(L, list)) and (None not in L)) i = 0 while (L[i] != None): j = L[i] L[i] = None i = j a = [None]*2 return (L == a + [-1] + a)