# CMU 15-112: Fundamentals of Programming and Computer Science Extra Practice for Unit 4 (Due never) Code Tracing (CT) and Reasoning Over Code (ROC) Exercises

This week we have included some extra OOP problems to further help you prepare for the upcoming midterm!
This is part2! Also see extra-practice4-ct-and-roc.html
These problems will help you prepare for hw4, quiz4, and the upcoming midterm. They are optional and you are encouraged to collaborate when working on them.
OOP (Object-Oriented Programming) Practice

1. OOP Practice #1 of 1:
# Write the class Dog so that the following test code passes: def testDogClass(): print("Testing Dog Class...", end='') snoopy = Dog("Snoopy") assert(snoopy.name == "Snoopy" and snoopy.energy == 10 and snoopy.isTired == False) assert(snoopy.speak() == "Woof my name is Snoopy and I am a good dog!") clifford = Dog("Clifford") assert(clifford.name == "Clifford" and clifford.energy == 10 and clifford.isTired == False) assert(clifford.speak() == "Woof my name is Clifford and I am a good dog!") snoopy.play() assert(snoopy.energy == 5) snoopy.play() assert(snoopy.energy == 0) assert(snoopy.isTired == True) assert(snoopy.play() == "I'm too tired please feed me first.") snoopy.feed(8) assert(snoopy.isTired == False) snoopy.play() assert(snoopy.energy == 3) print("Passed!") testDogClass()

Code Tracing (CT)
What will each of these print?

1. Trace #1:
import copy a = [1,2,3,4] (b,c) = (a, copy.copy(a)) print((a == b), (a == c)) print((a is b), (a is c)) print((a is b), (a is c)) a = [1,2] (b,c) = (a, copy.copy(a)) b += 10 c += 100 for L in [a,b,c]: print(L) a = [1,2] (b,c) = (a, copy.copy(a)) a += 1 b += 2 c += 3 a = c b = a for L in [a,b,c]: print(L) print() a = list(range(2,10,7)) (b, c) = (a, a[:2]) b += 3 a +=  a = a +  print(c + [b]) print(c.append(b)) print(a, b, c)

2. Trace #2:
import copy def f(a, b): a = copy.copy(a) a = b b = a return a + b a1 = a2 = list(range(5,7)) b1 = b2 = list(range(2)) a1 = f(a1, b1) print(a1, a2, b1, b2)

3. Trace #3:
def onesDigit(n): return n%10 def ct(L): for i in range(len(L)): L[i] += sum(L) + max(L) return sorted(L, key=onesDigit) a = [2,1,0] print(ct(a)) print(a)

4. Trace #4:
def ct(a): a = "foo" a, a = a, a 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(ct(lst)) print(lst)

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

1. RC #1 of 2:
def rc1(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])

2. RC #2 of 2:
import copy def rc(a): assert(sorted(a) == list(range(5,9))) b = copy.copy(a) for i in range(len(b)): b[len(b)-1-i] *= i return ((b == 18) and (min(a) == b) and (a > a))