CMU 15-110: Principles of Computing
Week8 Practice (Due never)
Contents:
1. Code Tracing
What will this code print? Figure it out by hand, then run the code to confirm. Then slightly edit the code and try again.
- Trace #1:
def ct1(L): rows = len(L) cols = len(L[0]) result = dict() for row in range(rows): for col in range(cols): key = L[row][col] if ((key == row) or (key == col)): if (key in result): result[key] += 1 else: result[key] = 1 return result # Look for the patterns, do not trace the whole thing! print(ct1([[1,2,3,0,6,9,0,2], [0,3,4,2,4,5,4,3], [7,3,2,4,2,7,1,5]]))
- Trace #2:
def ct2(d): s = set() t = set() for key in d: value = d[key] if (value in s): t.add(value) else: s.add(value) return t # Look for the patterns, do not trace the whole thing! print(ct2({ 'a':5, 'b':3, 'c':2, 'd':5, 'e':4, 'f':2, 'g':7, 'h':1, 'i':9, 'j':6, 'l':9, 'm':8, 'n':0, 'o':'wow!', 'p':42 }))
- Trace #3:
class Struct(object): pass def ct3(L): s = set() for rect in L: area = rect.width * rect.height s.add(area) return s rect1 = Struct() rect1.width = 10 rect1.height = 6 rect2 = Struct() rect2.width = 30 rect2.height = 3 rect3 = Struct() rect3.width = 30 rect3.height = 2 rect4 = Struct() rect4.width = 18 rect4.height = 2 rect5 = Struct() rect5.width = 18 rect5.height = 5 print(ct3([rect1, rect2, rect3, rect4, rect5]))