ProgrammingHardProduct-company MCQ pattern
What is printed?
What is printed?
def count_calls(fn):
def wrapper(*a):
wrapper.calls += 1
return fn(*a)
wrapper.calls = 0
return wrapper
@count_calls
def fib(n):
return n if n < 2 else fib(n - 1) + fib(n - 2)
print(fib(6), fib.calls)- A. 8 25
- B. 8 1
- C. 8 13
- D. 13 25
Correct answer: A. 8 25
The decorator replaces fib with wrapper, and the recursive calls inside fib also go through the global name fib, i.e. through wrapper – so every call is counted. Naive fib(6) makes 25 calls (C(n) = 1 + C(n − 1) + C(n − 2)). fib(6) = 8.
More Python Programming questions
- What is printed? python def make(): acc = [] for i in range(3): def f(x, i=i): return x i acc.append(f) acc.append(lambda x: x + i) return…
- What is printed? python class A: def go(self): return ["A"] class B(A): def go(self): return ["B"] + super().go() class C(A): def…
- What is printed? python def inner(): x = yield 1 y = yield x + 1 return x y def outer(): r = yield from inner() yield r yield from…
- What is printed? python def reg(name, seen={}, order=[]): if name not in seen: seen[name] = len(order) order = order + [name] return…
- What is printed? python def bucket(x, w): return x // w, x % w, int(x / w), -(-x // w) print(bucket(-7, 3), bucket(7, -3))
- What is printed? python d = {"b": 1, "a": 2, "c": 3} d["a"] = 9 d.update(b=7, d=4) d["c"] = d.pop("c") d.setdefault("a", 0) e = {d, "b"…