ProgrammingHardProduct-company MCQ pattern

What is printed?

What is printed?
def count_calls(fn):
    def wrapper(*a):
        wrapper.calls += 1
        return fn(*a)
    wrapper.calls = 0
    return wrapper
@count_calls
def fib(n):
    return n if n < 2 else fib(n - 1) + fib(n - 2)
print(fib(6), fib.calls)
  1. A. 8 25
  2. B. 8 1
  3. C. 8 13
  4. D. 13 25

Correct answer: A. 8 25

The decorator replaces fib with wrapper, and the recursive calls inside fib also go through the global name fib, i.e. through wrapper – so every call is counted. Naive fib(6) makes 25 calls (C(n) = 1 + C(n − 1) + C(n − 2)). fib(6) = 8.

More Python Programming questions

Exams that ask this topic