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


This note contains the Code Tracing problems from a recent quiz. We will discuss techniques for approaching these kinds of problems.
This note also contains Reasoning Over Code problems. We will not be covering these this semester, and they will typically not appear on quizzes or tests this semester. We include them here, though, for those of you who may wish to use them as a study or learning aid, or who may just enjoy the challenge they present.
  1. Code Tracing #1
    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
    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
    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
    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))