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)- A. False 4 [0, 1, 2, 3, 4] 2
- B. True 5 [0, 1, 2, 3, 99, 4] 2
- C. True 5 [0, 1, 2, 3, 4] 1
- 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
- What is printed? python class Seq: def init(self, n): self.n = n; self.calls = 0 def getitem(self, i): self.calls += 1 if i >= self.n…
- What is printed? python import heapq tasks = [(2, "write"), (1, "test"), (2, "ship"), (1, "plan")] h = [] for i, (p, name) in…
- What is printed? python x = -13 print(x >> 2, x // 4, ~x, x & 0xF, bin(x & 0xFF).count("1"), (-x) >> 2)
- What is printed? python def chain(nums, divisors): g = (n for n in nums) for d in divisors: g = (n for n in g if n % d) return list(g)…
- What is printed? python class V: def init(self, n, log): self.n, self.log = n, log def add(self, o): self.log.append("add"); return…
- What is printed? python log = [] def t(x): log.append(x); return x def f(a, b=t("d1"), args, c=t("d2"), kw): return a, b, args, c…