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


  1. Check 10.9
    Finish the function productOfPerfectSquares(n) that returns the product of all positive perfect squares less than or equal to the integer n. You must use the provided list comprehension and a call to the reduce function. Your function should be one line long.
    Note: The autograder for this problem will only consider the first two lines of your submission.
    from functools import reduce def productOfPerfectSquares(n): return [i**2 for i in range(1, int(n**0.5) + 1) if i**2 <= n] def testProductOfPerfectSquares(): print("Testing productOfPerfectSquares...", end="") assert(productOfPerfectSquares(10)==36) assert(productOfPerfectSquares(100)==13168189440000) assert(productOfPerfectSquares(99)==131681894400) assert(productOfPerfectSquares(1)==1) print("Passed!") testProductOfPerfectSquares() 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) student_code = '\n'.join(student_code.splitlines()[:2]) try: execCapture = captureIO() sys.stdout = execCapture sys.stderr = execCapture exec(student_code) if not "reduce(" in student_code: set_certificate(certificate_div_id, "No reduce") return for n in range(1,50): output = productOfPerfectSquares(n) certificate.append((output, type(output))) set_certificate(certificate_div_id, str(certificate)) except: set_certificate(certificate_div_id, "error")

  2. Back to notes