CMU 15-112: Fundamentals of Programming and Computer Science
Extra Practice for Unit 2 (Due never)
Code Tracing (CT) and Reasoning Over Code (ROC) Exercises
These problems will help you prepare for hw2 and quiz2. 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))
Reasoning Over Code (ROC)
Find values for the parameters so the functons return True:
- def rc1(n): if ((not isinstance(n, int)) or (n > 100)): return False total = 0 while (n > 0): total = 10*total + n%10 n //= 10 return (total == 42)
- def f(n): if (n == 0): return 1 n = abs(n) count = 0 while (n > 0): count += 1 n //= 10 return count def rc2(m): if (not(isinstance(m, int)) or (m < 0)): return False start = 0 while True: count = 0 for n in range(start, start+3): count += f(n) if (count > 9): break start += 1 return (m == start)
- def rc3(m): if ((not isinstance(m, int)) or (m < 0)): return False x = 1 while (x < m//2): x += 10 return (x + m == 60)
- def rc4(n): if (n == 0): return False count = 0 for x in range(0, 100, n): count += 1 return ((count == 5) and (x//10 == x%10 + 4))