#
CMU 15-110: Principles of Computing

Week5 Recitation (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 f(n): return n + 1 print(f(3) + f(5))**Trace #2:**def f(n): return n + 1 def g(n): return 10 * f(n) print(g(2)) print(g(2) + f(6))**Trace #3:**def f(n): result = '' if (n < 0): result += 'A' elif (n % 10 >= 5): result += 'B' if (n > 5): result += 'C' else: result += 'D' return result print(f(-5)) print(f(0)) print(f(25))**Trace #4:**def f(m, n): j = 0 k = 0 for i in range(m, n): j += i k += 1 return j*k print(f(3,6)) print(f(6,3))**distance(x1, y1, x2, y2)**

Write the function distance(x1, y1, x2, y2) that takes four int or float values x1, y1, x2, y2 that represent the two points (x1, y1) and (x2, y2), and returns the distance between those points as a float.def distance(x1, y1, x2, y2): return 42 # replace with your solution! def almostEqual(d1, d2): epsilon = 10**-7 return (abs(d2 - d1) < epsilon) def testDistance(): print('Testing distance()... ', end='') assert(almostEqual(distance(0, 0, 3, 4), 5)) assert(almostEqual(distance(-1, -2, 3, 1), 5)) assert(almostEqual(distance(-.5, .5, .5, -.5), 2**0.5)) print('Passed.') testDistance()**fabricYards(inches)**

Fabric must be purchased in whole yards. Write the function fabricYards(inches) that takes the number of inches of fabric desired, which you may assume is a non-negative int, and returns as an int the smallest number of whole yards of fabric that must be purchased.def fabricYards(inches): return 42 # replace with your solution! def testFabricYards(): print('Testing fabricYards()... ', end='') assert(fabricYards(0) == 0) assert(fabricYards(1) == 1) assert(fabricYards(35) == 1) assert(fabricYards(36) == 1) assert(fabricYards(37) == 2) assert(fabricYards(72) == 2) assert(fabricYards(73) == 3) print('Passed.') testFabricYards()**fabricExcess(inches)**

Write the function fabricExcess(inches) that takes the number of inches of fabric desired, which is a non-negative int, and returns the number of inches of excess fabric that must be purchased (as purchases must be in whole yards). Hint: you may want to use fabricYards, which you just wrote!def fabricExcess(inches): return 42 # replace with your solution! def testFabricExcess(): print('Testing fabricExcess()... ', end='') assert(fabricExcess(0) == 0) assert(fabricExcess(1) == 35) assert(fabricExcess(35) == 1) assert(fabricExcess(36) == 0) assert(fabricExcess(37) == 35) assert(fabricExcess(72) == 0) assert(fabricExcess(73) == 35) print('Passed.') testFabricExcess()

**Free Response (Problem-Solving)**