Data Structures & AlgorithmsVery hardTCS NQT Digital · closures
Problem: What does the following print?
Problem: What does the following print?
fs = [lambda: i for i in range(3)] print([f() for f in fs])
- A. [0, 1, 2]
- B. [0, 0, 0]
- C. [2, 2, 2]
- D. [1, 2, 3]
Correct answer: C. [2, 2, 2]
Lambdas capture the variable i, not its value at creation, so after the loop every function sees i = 2. Binding it with a default argument fixes this.
More Coding Interview Problems questions
- Problem: What does the following print? python print(len({1, 2, 3} & {2, 3, 4} | {5}))
- Problem: What does the following print? python print('10' < '9', 10 < 9)
- Problem: What does the following print? python print(int('12', 8) + int('0x1f', 16))
- Problem: How many strings of length 4 over {a, b} contain neither 'aa' nor 'bb' as a substring? Run the code. python from itertools import…
- Problem: What is the sum of Euler's totient phi(k) for k = 1 to 20? Run the code. python from math import gcd print(sum(sum(1 for g in…
- Problem: How many integers in [1, 100] have exactly 4 positive divisors? Run the code. python print(sum(1 for x in range(1, 101) if sum(1…