ProgrammingVery hardProduct company OA
What is printed?
What is printed?
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 acc
fs = make()
print([f(10) for f in fs])- A. [0, 12, 10, 12, 20, 12]
- B. [0, 10, 10, 11, 20, 12]
- C. [20, 12, 20, 12, 20, 12]
- D. [0, 10, 10, 10, 20, 10]
Correct answer: A. [0, 12, 10, 12, 20, 12]
A default argument is evaluated once, when the def statement runs, so each f freezes its own i (0, 1, 2) and returns 0, 10, 20. The lambdas have no default: they look i up in make's scope when they are finally called, after the loop has ended with i = 2, so all three return 12. Interleaved: [0, 12, 10, 12, 20, 12]. The option [0, 10, 10, 11, 20, 12] assumes the lambdas also capture the value at creation time.
More Python Programming questions
- 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"…
- What is printed? python a = [1, 2]; b = a; c = a[:] t = (a, c) a += [3] b = b + [4] c = 2 print(t[0] is a, b is a, t[1] is c, len(t[0])…