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


  1. Check 10.4
    Write the function safeFind(lst, index) which takes a list and an index. If the index is a valid index return lst[index]; otherwise, return None. You must use try/except in your answer.
    def safeFind(lst, index): pass def testSafeFind(): print("Testing safeFind()...", end="") assert(safeFind([1, 2, 3], 2) == 3) assert(safeFind([1, 2, 3], 5) == None) assert(safeFind([ ], 0) == None) print("Done.") testSafeFind() 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) if not "try:" in student_code or not "except:" in student_code: set_certificate(certificate_div_id, "No try except") return tests = [([0, 4, 4, 1], 0), ([3, 8], 5), ([10, 3, 9], 'foo'), ([0, 5, 2], 5), ([9], 5), ([6, 2, 3, 3], 2), ([1, 4, 2], 1), ([2], 5), ([10], 3), ([0, 5, 10, 1], 2)] for (lst, idx) in tests: output = safeFind(lst, idx) certificate.append((output, type(output))) set_certificate(certificate_div_id, str(certificate)) except: set_certificate(certificate_div_id, "error")

  2. Back to notes