ProgrammingHardGATE CS · Product-company placement
What is printed?
What is printed?
cache = {}
def ways(n):
if n < 0: return 0
if n == 0: return 1
if n not in cache:
cache[n] = ways(n - 1) + ways(n - 2) + ways(n - 3)
return cache[n]
print(ways(5), len(cache))- A. 13 5
- B. 8 5
- C. 13 6
- D. 24 5
Correct answer: A. 13 5
ways(n) counts step sequences of 1, 2 or 3 (tribonacci): 1, 1, 2, 4, 7, 13 for n = 0..5. The cache stores n = 1..5 (n = 0 and negatives return early), so 5 entries.
More Python Programming questions
- What is printed? python def perms(s): if len(s) <= 1: return [s] out = [] for i, c in enumerate(s): for p in perms(s[:i] + s[i + 1:])…
- What is printed? python def makeops(): ops = {} for name, sym in [("add", "+"), ("mul", "")]: ops[name] = eval(f"lambda a, b: a {sym} b")…
- What is printed? python x = 1 def f(): return x def g(): x = 2 return f() def h(): global x x = 3 return f() print(g(), h(), f())
- What is printed? python class Celsius: def init(self, t=0): self.t = t def get(self, obj, owner): return self if obj is None else obj.c…
- What is printed? python class Vec: def init(self, c): self.c = c def mul(self, k): return Vec((x k for x in self.c)) rmul = mul def…
- What is printed? python class Ordered: def init(self, v): self.v = v def lt(self, o): print("lt", end=" ") return self.v < o.v def…