ProgrammingVery hardTCS CodeVita · Infosys HackWithInfy
What is printed?
What is printed?
def outer():
res = []
for i in range(3):
res.append(lambda: i)
return [f() for f in res]
def outer2():
return [(lambda j: (lambda: j))(i) for i in range(3)]
print(outer(), [f() for f in outer2()])- A. [0, 1, 2] [0, 1, 2]
- B. [2, 2, 2] [2, 2, 2]
- C. [0, 1, 2] [2, 2, 2]
- D. [2, 2, 2] [0, 1, 2]
Correct answer: D. [2, 2, 2] [0, 1, 2]
Lambdas capture the variable i, not its value at creation, so every call sees the final i = 2. In outer2 each lambda is created inside a function whose argument fixes the value per iteration.
More Python Programming questions
- What is printed? python print(10 18 % 7, (10 18 + 2) // 4, -(2 63) // (2 62))
- What is printed? python lst = list(range(5)) lst[1:4] = [] try: lst[::2] = [9, 9] except ValueError: print('ValueError', lst)
- What is printed? python def dedupe(a): if not a: return 0 k = 1 for i in range(1, len(a)): if a[i] != a[k - 1]: a[k] = a[i] k += 1 return…
- What is printed? python def firsttrue(lo, hi, ok): while lo < hi: mid = (lo + hi) // 2 if ok(mid): hi = mid else: lo = mid + 1 return lo…
- What is printed? python def search(a, t): lo, hi = 0, len(a) - 1 while lo <= hi: mid = (lo + hi) // 2 if a[mid] == t: return mid if a[lo]…
- What is printed? python import bisect a = sorted(['10', '9', '100', '20']) print(a, bisect.bisectleft(a, '9'), [int(x) for x in a])