CMU 15-112: Fundamentals of Programming and Computer Science
Class Notes: Code Tracing and Reasoning Over Code


We'll only cover CTs during week 1! You can ignore ROCs for now, unless you want to get a jump-start for later.
  1. Code Tracing #1
    What does the following code print? Solve this without running it, and then check your answer!
    def ct1(x, y): print((x//10) % ((y%10)**3)) if (x > y): return isinstance(x/10, type(x)) print(ct1(137,42)) print(ct1(42, 731))

  2. Code Tracing #2
    What does the following code print?
    def f(z): return 2*z def g(z): z += 1 return z/2 def h(z): if (z > 3): return z + f(g(z)) else: return g(z) def ct2(z): print(h(z-1)) z *= 2 return h(z) print(ct2(3))

  3. Reasoning Over Code #1
    What value for n will make rc1 return True?
    def rc1(n): t = n//1000 return ((n >= 100000) and (n <= 333333) and (t != 112) and (t % 112 == 0) and (t == n%1000)) print('rc1:', rc1(42))

  4. Reasoning Over Code #2 What values for x and y will make rc2 return True?
    def f(x1, x2, n): d1 = (x1 // (10**n)) % 10 d2 = (x2 // (10**n)) % 10 if ((d1 > d2) and (d1 > 5)): return d1 elif (d2 > d1): return d2 elif ((d1 == 0) and (d2 == 0)): return 42 elif ((d1 == 0) or (d2 == 0)): return -10**10 else: return 0 def rc2(x, y): z = 100*f(x,y,2) + 10*f(x,y,1) + f(x,y,0) return ((f(x,y,3) == 42) and (z == 206)) print('rc2:', rc2(42, 99))