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


  1. Check 10.6
    Write the decorator function double(f) which takes a function (f) that returns a number, and returns a function that returns double that number. Do not change addNumbers or echo directly!
    def double(f): pass @double def addNumbers(x, y): return x + y @double def echo(n): return n def testDouble(): print("Testing double()...", end="") assert(addNumbers(4, 6) == 20) assert(addNumbers(0, 3) == 6) assert(echo(10) == 20) assert(echo(-1) == -2) print("Done.") testDouble() 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 def make_certificate(student_code_div_id, certificate_div_id): certificate = [] student_code = get_student_code(student_code_div_id) try: execCapture = captureIO() sys.stdout = execCapture sys.stderr = execCapture exec(student_code) @double def addMany(*args): return sum(args) tests = [[20, 16, 6, 7, 14, 19, 7, 8, 1, 13, 4, 10, 6, 4], [], [10, 19, 6, 8, 2, 5, 20, 5, 3, 5, 0, 6, 12, 5, 5], [3, 16, 1, 2], [10, 3, 5, 14, 3, 1, 7], [7, 9, 13, 20, 18, 11, 10, 17, 16, 6, 18, 1, 4, 1], [1, 13, 10, 8, 4, 18, 6, 17, 16, 5, 16, 13, 12, 13, 19], [2, 2, 12, 11, 1, 18, 18, 8, 11, 17, 6, 7, 8, 13], [6, 7, 20, 2, 12, 8, 5, 13], [14, 12, 7, 17, 15, 13, 8, 20, 15, 13, 3, 14, 12, 1, 17], [3, 2, 4, 0, 6, 8], [], [13, 1, 4, 15, 2, 9, 2, 4, 18], [20, 15, 15, 0, 12, 19, 3, 0, 1, 3, 13], [7, 9, 3, 18, 5, 6, 11, 2, 17, 5, 11, 17, 13], [14, 1, 0, 17, 16, 3, 19, 17, 4, 13, 3], [19, 15, 19, 9, 19, 14, 2, 7, 17], [20, 13, 4], [12, 14, 2, 5, 15, 9], [19, 12, 15, 11], [], [17, 20, 16, 6, 9, 10, 20, 2, 7, 6, 16, 0], [20, 16, 4, 19, 17, 9, 2, 4, 13], [15, 18, 8, 0, 19, 9], [11, 2, 16, 12, 6, 10, 10, 3, 20, 10]] for test in tests: output = addMany(*test) certificate.append((output, type(output))) set_certificate(certificate_div_id, str(certificate)) except: set_certificate(certificate_div_id, "error")

  2. Back to notes