Data Structures & AlgorithmsModerateAccenture · Cognizant coding round pattern
Problem: Find the bug: a list of multiplier functions is built in a loop with lambdas.
Problem: Find the bug: a list of multiplier functions is built in a loop with lambdas.
fs = [lambda x: x * i for i in range(1, 4)] gs = [lambda x, i=i: x * i for i in range(1, 4)] print([f(10) for f in fs], [g(10) for g in gs])What is printed?
- A. [30, 30, 30] [10, 20, 30]
- B. [30, 30, 30] [30, 30, 30]
- C. [0, 10, 20] [10, 20, 30]
- D. [10, 20, 30] [10, 20, 30]
Correct answer: A. [30, 30, 30] [10, 20, 30]
Python closures capture the variable i, not its value at creation time (late binding); after the comprehension i is 3, so every lambda in fs multiplies by 3. A default argument i=i is evaluated when each lambda is created, freezing 1, 2, 3. The same pitfall appears with callbacks created in loops.
More Coding Interview Problems questions
- Problem: Find the bug: even values are removed from a list while iterating over that same list. python nums = [2, 4, 4, 6, 5, 8] for x in…
- Problem: n ≤ 2·10⁵ values; count pairs i < j with (a[i] + a[j]) divisible by k. The O(n²) check times out; bucket by remainder and pair…
- Problem: A divide-and-conquer routine makes 3 recursive calls on halves and does linear extra work: T(n) = 3T(n/2) + n. The code evaluates…
- Problem: A sliding-window routine has a while loop nested inside a for loop. For a 12 000-character string, how many inner (left-pointer)…
- Problem: Find the inefficiency: two BFS versions on an R × C open grid. One marks a cell visited when it is pushed, the other only when it…
- Problem: Find the bug: binary search for the LAST x in [lo, hi] with ok(x) true (here the largest x with x² ≤ 30). The first version uses…