CMU 15-112: Fundamentals of Programming and Computer Science
Extra Practice for Week 1 part 2 (Due never)
Code Tracing (CT) Exercises
These problems will help you prepare for hw2 and quiz1. They are optional and you are encouraged to collaborate when working on them.
Code Tracing (CT)
What will each of these print?
def ct1(n,m): for i in range(n, 7): for j in range(m, -2, -1): i = abs(i) j = abs(j) if i % 2 == 0: print("even", i) elif i > 0: print("foo", i) if j % 2 == 1: print("odd", j) if j > 0: print("bar", j) print("almost done!") print("done!") ct1(5,-1)
def ct2(m, n): total = 0 for x in range(m, n+1, 3): print('x =', x) total += x for y in range(m, m+2): print('y = ', y) total += y return total print(ct2(1,9))
def ct3(z): total = 0 for y in range(z,1,-1): if (y % 2 == 0): print('skip y =', y) continue total += y if (total > 20): print('break at y =', y) break return total print(ct3(10))
def ct4(n, m): for i in range(1, 2*n, n): for j in range(-m, -1, m//3): if(i % 4 == j): print("mod", i, j) if(i == j): print("equal", i, j) elif(j > i): print("greater", i, j) else: break ct4(2, -5)
def ct5(x): y = 3 while True: print(y, end=' ') for z in range(1, x*y, 2): if (z % 3 == 1): print(z, end=' '); continue y += x if (y % 5 > 0): print(y, end=' ') break print(y, end=' ') if (y > 10): return x y += 1 print(ct5(7))