Data Structures & AlgorithmsModerateAmazon · Microsoft OA
Edge case: A generator expression is consumed twice.
Edge case: A generator expression is consumed twice.
g = (x * x for x in range(4)) print(sum(g), sum(g))What is printed?
- A. 14 14
- B. 0 14
- C. It raises StopIteration
- D. 14 0
Correct answer: D. 14 0
A generator can be iterated only once. The first sum consumes 0 + 1 + 4 + 9 = 14; the second finds it exhausted and returns 0 (sum of nothing) without raising. Use a list if the values are needed twice.
More Coding Interview Problems questions
- Problem: Sort students by grade (descending), breaking ties by name (ascending), using two passes of Python's STABLE sort. python s =…
- Problem: Find the length of the SHORTEST subarray with sum ≥ k when values may be negative (monotonic deque over prefix sums). python from…
- Problem: Longest subarray whose max − min ≤ limit, using two monotonic deques. python from collections import deque def longest(a, lim)…
- Problem: Count subarrays whose maximum lies in [L, R] in one pass. python def count(a, L, R): lastbad = lastok = -1; res = 0 for i, x in…
- Problem: Shortest path (in steps) from the top-left to the bottom-right cell of a grid where 1 is a wall, if you may remove at most k…
- Problem: A lock has 4 wheels of digits 0–9; one move turns one wheel by ±1 (wrapping 9↔0). Starting at '0000', find the fewest moves to…