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)- A. [2, 3, 2, 3, 4]
- B. [2, 3, 4]
- C. [2, 3]
- 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
- What is printed? python def deco(f): def wrapper(a, k): wrapper.calls += 1 return f(a, k) wrapper.calls = 0 return wrapper @deco def h()…
- What is printed? python def decoratorwithargs(prefix): def actual(f): def wrapper(a, k): return prefix + str(f(a, k)) return wrapper…
- What is printed? python class A: def init(self): self.x = 1 def enter(self): return self def exit(self, a): self.x = 0 return False with…
- What is printed? python class R: @property def x(self): return 5 r = R() try: r.x = 10 except AttributeError: print("AttributeError")
- What is printed? python try: raise TypeError("t") except (ValueError, TypeError) as e: print("caught", type(e).name)
- What is printed? python def f(): return 1, 2, 3 a, b, c = f() print(a, b, c) x = f() print(type(x), x)