ProgrammingHardGATE CS · Product-company placement
What is printed?
What is printed?
adders = [lambda x, n=n: x + n for n in range(3)] mults = list(map(lambda n: (lambda x: x * n), range(3))) print([f(10) for f in adders], [g(10) for g in mults])
- A. [12, 12, 12] [20, 20, 20]
- B. [10, 11, 12] [20, 20, 20]
- C. [12, 12, 12] [0, 10, 20]
- D. [10, 11, 12] [0, 10, 20]
Correct answer: D. [10, 11, 12] [0, 10, 20]
Both fix the late-binding issue: a default argument captures n's current value, and creating each lambda inside a separate function call (the outer lambda) gives each its own n.
More Python Programming questions
- What is printed? python def outer(): fs = [] for i in range(3): def f(j=None): return i if j is None else j fs.append(f) if i == 1: break…
- What is printed? python x = "global" def f(): return [x for in range(1)][0] def g(): x = "local" return (lambda: x)() def h(): return…
- What is printed? python try: r = [1 / x for x in [1, 0, 2]] except ZeroDivisionError: r = "partial?" g = (1 / x for x in [1, 0, 2]) out =…
- What is printed? python def f(x): if x > 0: return x print(f(1), f(-1), f(0) or "zero", f(2) and f(-2))
- What is printed? python print(repr([] or {} or 0 or ""), "a" and "b" or "c", "" and 1 or 0, not "0")
- What is printed? python def f(a, b): return a // b if b else None vals = [(7, 2), (-7, 2), (7, 0), (7.0, -2)] print([f(p) for p in vals]…