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


These problems will help you prepare for hw1 and test1. They are optional and you are encouraged to collaborate when working on them.
Code Tracing (CT)
What will each of these print?

  1. # CT1: def f(x): print('f', x) x += 1 return (x**2) // 10 def g(x): print('g', x) x = (7 * x) % 5 return f(x + 3) x = 5 print(f(g(f(x))) + x)

  2. # CT2: import math print(1 * 2 // 1 + 4 - 3) print(2**4/10 + (3 + 2**3) // 10) print(round(8/3) + max(8/3, math.ceil(8/3)))

  3. # CT3: def f(x, y): if (x > y): if (x > 2 * y): print('A') else: print('B') print('C') def g(x, y): if (abs(x % 10 - y % 10) < 2): print('D') elif (x % 10 > y % 10): print('E') else: if (x // 10 == y // 10): print('F') if (x // y > 0): print('G') f(3,4) g(1,2)

  4. # CT4: def f(x): return 3 * x - 2 def g(x): return f(x + 3) def h(x): print(f(x - 2)) x -= 2 print(g(x)) x %= 4 return f(g(x) % 6) // 2 print(3 + h(4))

  5. # CT5: def f(x): return 2 * x + 1 def g(x): return f(x // 2) def h(x): if (x % 2 == 0): return f(x + g(x)) else: return f(x) - g(x) def ct(x): print(h(x)) print(h(x + 1)) print(ct(5))

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

  1. def rc1(x, y): return ((100 > x > y > 0) and (x + y == 10) and (y // x == x // y - 1))

  2. def rc2(x): return ((type(x) == int) and (int(round(x**0.5))**2 == x) and (x//10 == x%10 + 2))

  3. def rc3(x, y): return ((type(x) == type(y) == int) and (100 > x > y > 0) and (x % 10 == y // 10) and (y % 10 == x // 10) and (x - y == 9))

  4. def almostEqual(x, y): return abs(x - y) < 10**-9 def rc4(n): if ((not isinstance(n, int)) or (n < 100) or (n > 999)): return False a = n % 10 b = n // 10 return (almostEqual(b**0.5, a) and (a + b == 42))

  5. def rc5(x): assert(type(x) == int) return ((x % 10 == x // 10 - 1) and (x // 9 * 9 == x))