ProgrammingVery hardProduct company OA

What is printed?

What is printed?
from functools import lru_cache
@lru_cache(maxsize=None)
def path(n):
    return [0] if n == 0 else path(n - 1) + [n]
p = path(3)
p.append(99)
q = path(3)
r = path(4)
print(q is p, len(q), r, path.cache_info().hits)
  1. A. False 4 [0, 1, 2, 3, 4] 2
  2. B. True 5 [0, 1, 2, 3, 99, 4] 2
  3. C. True 5 [0, 1, 2, 3, 4] 1
  4. D. True 5 [0, 1, 2, 3, 99, 4] 4

Correct answer: B. True 5 [0, 1, 2, 3, 99, 4] 2

lru_cache stores the returned OBJECT, not a copy. p is the cached list for 3, so p.append(99) corrupts the cache: the next path(3) is a hit that returns the very same 5-element list, and path(4) is built from it as [0, 1, 2, 3, 99, 4]. Hits: the first path(3) is four misses (3, 2, 1, 0); q is hit 1; path(4) is a miss whose inner path(3) is hit 2. Never return a mutable from a cached function (return a tuple instead).

More Python Programming questions

Exams that ask this topic