# CMU 15-110: Principles of Computing 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.

• Traces #1-4 from Recitation
See Code Tracing examples here.

• Trace #5:
def f(z): m = 0 while (m < z): m = (m + 1)*2 return m-z print(f(25)) print(f(f(25)))

• Trace #6:
def f(n): r = 0 while (n > 0): r = 10*r + (n%10) n //= 10 return r print(f(12345)) print(f(10200))

• Trace #7:
def f(n): k = 0 while (k**2 < n): k += 1 return k**2 print(f(99)) print(f(101))

• Trace #8:
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))

• Trace #9:
def f(s): t = s + s.replace('th', '') t += chr(ord('a') + len(s)) for c in 'unshift': if (c not in t): t += c return t print(f('this '))

• Trace #10:
def encode(s): result = '' for c in s: result += chr(ord(c) + 1) return result print(encode('abc xyz 123')) # note: chr(32) is ' ', chr(33) is '!', chr(123) is '{'

• Trace #11:
def decode(s): result = '' for c in s: result += chr(ord(c) - 1) return result print(decode('bcd!yz{!234'))