ProgrammingHardCognizant GenC · TCS NQT
What is printed?
What is printed?
from functools import lru_cache
calls = 0
@lru_cache(maxsize=None)
def f(n):
global calls
calls += 1
if n < 2:
return n
return f(n - 1) + f(n - 2)
print(f(30), calls)- A. 832040 59
- B. 1346269 31
- C. 832040 60
- D. 832040 31
Correct answer: D. 832040 31
With the cache each f(n) for n = 0..30 runs its body once, so calls is 31; f(30) is 832040. Without the cache the same call would take about a million calls.
More Python Programming questions
- What is printed? python def greedy(coins, amt): cnt = 0 for c in sorted(coins, reverse=True): cnt += amt // c amt %= c return cnt if amt…
- What is printed? python import bisect def lis(a): t = [] for x in a: i = bisect.bisectleft(t, x) if i == len(t): t.append(x) else: t[i] =…
- A list a is sorted in ascending order and may contain duplicates. Using bisectleft and bisectright from the bisect module, which…
- A Python list q holds n items. A loop repeatedly does x = q.pop(0) until q is empty. What is the total time cost of the loop in big-O terms?
- What is printed? python def rob(a): p, c = 0, 0 for x in a: p, c = c, max(c, p + x) return c print(rob([2, 7, 9, 3, 1]), rob([5]), rob([]))
- What is printed? python def ed(a, b): prev = list(range(len(b) + 1)) for i in range(1, len(a) + 1): cur = [i] + [0] len(b) for j in…