ProgrammingHardTCS NQT · Infosys pattern

What is printed?

What is printed?
from functools import lru_cache
calls = []
@lru_cache(maxsize=None)
def f(n):
    calls.append(n)
    return n * n
f(2); f(3); f(2); f(3); f(4)
print(calls)
  1. A. [2, 3, 2, 3, 4]
  2. B. [2, 3, 4]
  3. C. [2, 3]
  4. D. [4, 3, 2]

Correct answer: B. [2, 3, 4]

lru_cache memoizes results by argument. The first calls with 2, 3 and 4 actually run the function body (appending to calls); the repeated calls f(2) and f(3) are served straight from the cache without re-running the body.

More Python Programming questions

Exams that ask this topic