Extra Practice for Week 5 (Due never) Code Tracing (CT) and Reasoning Over Code (ROC) Exercises


These problems will help you prepare for the upcoming quizzes, midterms, and final exam. They are optional and you are encouraged to collaborate when working on them.
Code Tracing (CT)
What will each of these print?

  1. Trace #1:
    import copy def ct1(L): a = L b = copy.copy(L) c = copy.deepcopy(L) b[1][1] = c[0][0] c[1].append(b[1][0]) a[0] = b[1] a[0][0] += b.pop()[0] return a,b,c L = [[1],[2,5]] for val in ct1(L): print(val) print(L)

  2. Trace #2:
    def ct2(a): a[1] = "foo" a[0], a[2] = a[2], a[0] print(a) b = a b.extend([42, "wow" ]) b.pop() print(b) c = [] + b c[1:-1] = ["Hello" , "World" ] return c lst = [15, "1" , "twelve" ] print(ct2(lst)) print(lst)

  3. Trace #3:
    import copy def ct3(L): a = L b = copy.copy(L) c = copy.deepcopy(L) b[0] = a[1] * a[1][0] a[0][0] += a.pop()[0] b[1] = c[0] return b # Be careful to get the brackets and commas right! L = [[1],[2],[3]] print(ct3(L)) print(L)

  4. Trace #4:
    import copy def ct4(L): a = L b = copy.copy(L) c = copy.deepcopy(L) a[0] = b[1] b[1][1] = c[0] c[1].append(b[1]) a[0][0] += (b[1].pop())[0] return (a,b,c) # Be careful to get the brackets and commas right! for val in ct4([[1],[2,5]]): print(val) # prints 3 lines

  5. Trace #5:
    import copy def ct5(a): b = a (a, c, d) = (b + [b[0]], copy.copy(b), copy.deepcopy(b)) d[1] = b[0] c[1] = d[0] b = b[0:1] + b[1:] b[0] = [3,4] a[0] += [5] c[1][0] = 1 + b[0][1] a[0][0] = 6 + d[1][0] for (s,L) in (("a",a), ("b",b), ("c",c), ("d",d)): print(s,L) a = [list(range(2-i)) for i in range(2)] print("start:", a) ct5(a) print("end:", a)

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

  1. RC #1 of 4:
    def rc1(n): assert((isinstance(n, int)) and (100 <= n <= 999)) (n, r, c) = (n//100, n//10%10, n%10) L = [([0] * c) for row in range(r)] # note col is the outer loop for col in range(c): for row in range(r): L[row][col] = n n += 1 return ((L[0][2] - L[0][0] == 10) and (sum([len(R) for R in L]) == 20) and (sum(L[0]) == 42)) print(rc1(42)) # replace 42 with answer

  2. RC #2 of 4:
    def rc2(n): assert(isinstance(n, int) and (n > 0)) (d, total) = (0, 0) while (total < 100): (d, total) = (d+1, 0) a = [d] * d b = [a] * d # note: bad way to make a 2d list for i in range(d): for j in range(d): total += b[i][j] return (n == d) print(rc2(42)) # replace 42 with answer

  3. RC #3 of 4:
    def rc3(n): a = [[(r+c) for c in range(n)] for r in range(n)] b = [a[i][i] for i in range(n)] return (sum(b) == 20) print(rc3(42)) # replace 42 with answer

  4. RC #4 of 4:
    def rc4(L): assert(sorted(L) == sorted(range(len(L)))) result = [] for i in range(len(L)): m = L[i] for j in range(i, len(L)): if (L[j] > m): m = L[j] result.append(m) return (result == [3, 3, 2, 1]) print(rc4(42)) # replace 42 with answer