ProgrammingHardInfosys HackWithInfy · TCS CodeVita

What is printed?

What is printed?
def make():
    memo = {}
    def fib(n):
        if n in memo:
            return memo[n]
        memo[n] = n if n < 2 else fib(n - 1) + fib(n - 2)
        return memo[n]
    return fib
f = make()
print(f(50), len(f.__closure__))
  1. A. 12586269025 1
  2. B. 12586269025 2
  3. C. 12586269025 3
  4. D. 12586268025 2

Correct answer: B. 12586269025 2

fib refers to memo and to itself, so its closure holds two cells. fib(50) is 12586269025, and the memo keeps the recursion linear.

More Python Programming questions

Exams that ask this topic