ProgrammingVery hardGATE CS · Product-company placement
What is printed?
What is printed?
def f(n, memo={}):
if n in memo:
return memo[n]
r = n if n < 2 else f(n - 1) + f(n - 2)
memo[n] = r
return r
f(10)
print(len(f.__defaults__[0]), f(5, {}), len(f.__defaults__[0]))- A. 11 5 6
- B. 0 5 0
- C. 10 5 10
- D. 11 5 11
Correct answer: D. 11 5 11
The mutable default acts as a persistent cache: f(10) stores n = 0..10 (11 keys). Passing an explicit {} for f(5) uses a separate dict, and its recursive calls use the default, already filled, so the default is unchanged.
More Python Programming questions
- What is printed? python def f(): x = 1 def g(): return x x = 2 return g def h(): for x in [1, 2]: pass return lambda: x print(f()(), h()())
- What is printed? python class Node: def init(self, v, nxt=None): self.v, self.nxt = v, nxt def iter(self): n = self while n: yield n.v n =…
- What is printed? python import heapq h = [5, 1, 4] heapq.heapify(h) heapq.heappush(h, 0) small = heapq.heappop(h) print(small, h[0]…
- What is printed? python from collections import deque d = deque([1, 2, 3], maxlen=3) d.append(4) d.appendleft(0) d.rotate(1)…
- What is printed? python from collections import namedtuple P = namedtuple("P", "x y", defaults=[0]) p = P(1) q = p.replace(y=5) print(p…
- What is printed? python from dataclasses import dataclass, field @dataclass class Item: name: str tags: list = field(defaultfactory=list)…