CMU 15-112: Fundamentals of Programming and Computer Science
Extra Practice for Week 2 (Due never)
Code Tracing (CT) and Reasoning Over Code (ROC) Exercises
These problems will help you prepare for quiz2. They are optional and you are encouraged to collaborate when working on them.
Code Tracing (CT)
What will each of these print?
- def ct1(s, t): result = "" for c in s: if (c.upper() not in "NO!!!"): i = t.find(c) if (result != ""): result += ":" result += "%d%s%s%s" % (i, c, s[i], t[i]) return result print(ct1("net", "two"))
- def ct2(s): result = "" d = ord("a") for c in s.lower(): if (c.isalpha() and (ord(c) >= d)): result += str(ord(c) - d) + chr(d) d += 1 return result print(ct2("Be a CA?!?"))
- def ct3(s): result = "" while (len(s) > 1): result += s[:1] + s[2:4] + "." s = s[1:-1:2] return result + s print(ct3("abcdefghi"))
- def ct4(s, n): result = "" d = 0 while (n > 0) and (len(s) > 0): if (s[-1].isdigit()): result += str((n%10)%int(s[-1])) else: result += chr(ord('D')+d) n //= 10 s = s[1:-1] d += 1 return result print(ct4("abc3c3", 2468))
Reasoning Over Code (ROC)
Find values for the parameters so the functons return True:
- def rc1(n): assert(type(n) == int) s = str(n) return ((2000>n>1000) and (n == int(s[0]*len(s))))
- def rc2(s, t, n): q = "" for i in range(len(s)): q += t[(i+n)%len(t)] print(q) return ((len(s) == 2*len(t)) and (not s.startswith(t)) and (q == s))
- import string def rc3(n,k,x): s = "ab\tc\\d" assert(len(s) == n) assert(s[k] in string.whitespace) assert(s.find("b") == s.find("e") + x) return True
- def rc4(s): assert (s[0] == "d" and len(s) == 5) for i in range(1, len(s)): if (ord(s[i]) != (i + ord(s[i-1]))): #1 + d return False return True