CMU 15-112: Fundamentals of Programming and Computer Science
Extra Practice for Week 1 (Due never)
Code Tracing (CT) Exercises
These problems will help you prepare for hw1 and quiz1. They are optional and you are encouraged to collaborate when working on them. We may add some loop problems here on Friday.
Code Tracing (CT)
What will each of these print?
- # 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)
- # 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)))
- # 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)
- # 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))
- # 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))