CMU 15-112 Spring 2019: Fundamentals of Programming and Computer Science
Check 9.3


  1. Check 9.3
    The following program has one bug in it. Use your debugging skills to find and fix that bug!
    def countVowels(s): if len(s) == 0: return 0 else: num = 1 if s[0] in "aeiou" else 0 return num + countVowels(s) def testCountVowels(): print("Testing countVowels()...", end="") assert(countVowels("abcde") == 2) assert(countVowels("i") == 1) assert(countVowels("k") == 0) assert(countVowels("") == 0) print("Done.") testCountVowels() import sys def set_certificate(certificate_div_id, certificate): document[certificate_div_id].textContent = certificate def get_student_code(student_code_div_id): raw_student_code = document[student_code_div_id].textContent return window.patchCodeToCheckTimeout(raw_student_code, 'check_timeout();'); class captureIO: def __init__(self): self.captured = [] def get_output(self): out = "" for c in self.captured: out += str(c) return out def write(self, data): self.captured.append(data) def flush(self): pass test_rec = """ certificate = [] def inject_counters(): def callCounter(f): f.calls = 0 f.is_recursive = False def g(*args): f.calls += 1 initial_calls = f.calls out = f(*args) if (f.calls > initial_calls): f.is_recursive = True return out return g, f g = globals() current_objects = list(g.items()) originals = [] for name, obj in current_objects: try: if callable(obj): g[name], original = callCounter(obj) originals.append(original) except: pass return originals def did_recur(originals): return any(map(lambda f: f.is_recursive, originals)) originals = inject_counters() countVowels("abcde") recurs = did_recur(originals)""" def make_certificate(student_code_div_id, certificate_div_id): student_code = get_student_code(student_code_div_id) try: execCapture = captureIO() sys.stdout = execCapture sys.stderr = execCapture exec(student_code+"\n"+test_rec, globals()) if recurs: tests = ['.\\\x0b!)4rlk', '03W^+iqprMza', "3Y\x0cJhaXW 'Q", 'J?1GJ/o', '', 'n\\+g', '\rTv BEzq-`\t', 'D5Q0fQ@ VYy*', '', 'Spdn|]\nXUNH', 'aID0@{u6', ',z|yylh)p'] test1, test5 = "aeiou", "aeugfaeioa" test2, test3, test4 = "aba", "", "hjk" tests.extend([test1, test2, test3, test4, test5]) for test in tests: output = countVowels(test) certificate.append((output, type(output))) set_certificate(certificate_div_id, str(certificate)) else: set_certificate(certificate_div_id, "Not Recursive") except: set_certificate(certificate_div_id, "error")

  2. Back to notes