Data Structures & AlgorithmsHardGoogle · Flipkart interview
Edge case: lambdas created in a loop (closures).
Edge case: lambdas created in a loop (closures).
fs = [lambda: i * 10 for i in range(3)] gs = [lambda i=i: i * 10 for i in range(3)] print([f() for f in fs], [g() for g in gs])What is printed?
- A. [0, 10, 20] [0, 10, 20]
- B. [20, 20, 20] [0, 10, 20]
- C. [20, 20, 20] [20, 20, 20]
- D. [0, 10, 20] [20, 20, 20]
Correct answer: B. [20, 20, 20] [0, 10, 20]
Closures capture the VARIABLE i, not its value, and look it up when called, after the comprehension finished with i = 2: [20, 20, 20]. A default argument is evaluated at definition time, freezing each value: [0, 10, 20].
More Coding Interview Problems questions
- Edge case: JavaScript event-loop ordering of synchronous code, a promise callback and a timer. javascript const out = []; out.push("A")…
- Problem: Split an array (duplicates allowed) into the most chunks such that sorting each chunk separately and concatenating gives the…
- Problem: Detect a 132 pattern (i < j < k with a[i] < a[k] < a[j]) in O(n) by scanning from the right with a stack. python def has132(a)…
- Problem: A single-threaded CPU log has entries 'id:start:t' and 'id:end:t' (an end at t covers time unit t). Functions can call each…
- Problem: Evaluate an expression with +, −, , / (integer division truncating toward zero) and no parentheses, using a stack. python def…
- Problem: Find every start index in s of a substring that is a concatenation of all the given words (each exactly once, any order; all…