CMU 15-110: Principles of Computing
Week3 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 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))
- Trace #2:
def f(z): m = 0 while (m < z): m = (m + 1)*2 return m-z print(f(25)) print(f(f(25)))
- Trace #3:
def f(n): result = '' sides = n center = 1 for row in range(n): for col in range(60): if (row%2 == 0): result += '~' elif (col%2 == 0): result += '*' else: result += ':' result += '\n' # add a newline to the string! return result print(f(7))
- Trace #4:
# team-hw ct1: def f(n): r = 0 while (n > 0): r = 10*r + (n%10) n //= 10 return r print(f(12345)) print(f(10200))
- Trace #5:
# team-hw ct2: def f(n): k = 0 while (k**2 < n): k += 1 return k**2 print(f(99)) print(f(101))
- Trace #6:
# team-hw ct3: def f(n, bits): maxValue = 2**bits - 1 if (n > maxValue): return 'Not enough bits!' result = '' for k in range(bits-1, -1, -1): kthBit = n // 2**k % 2 result += str(kthBit) return result print(f(0,4)) print(f(3,4)) print(f(6,4)) print(f(15,4)) print(f(16,4))
- drawGrid(rows, cols)
Using the CS Academy sandbox, write the functiondrawGrid(rows, cols)
so that it draws a grid that fills the canvas with the given number of rows and cols. For example, drawGrid(5, 5) draws this:
and drawGrid(20, 10) draws this (note: 20 rows and 10 cols, not vice versa):
- rockPaperScissorsLizardSpock()
Write the functionrockPaperScissorsLizardSpock()
that works just like our rockPaperScissors case study, but includes Lizard and Spock, like the game here.
Free Response (Problem-Solving)