CMU 15-112: Fundamentals of Programming and Computer Science
Extra Practice for Week 4 (Due never) Code Tracing (CT) Exercises


These problems will help you prepare for the upcoming quiz 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)