A Generator You Can send() To

Hard ⏱ 18 min 38% acceptance ★★★★★ 4.8
Coroutine-style: write accumulator() — a generator that receives numbers via .send(n) and yields the running total each time. The caller must prime it with next(gen) first (yielding an initial 0). This is the pre-async coroutine pattern interviews still probe.

Examples

Example 1
Input
g = accumulator(); next(g); g.send(5); g.send(3)
Output
0, then 5, then 8
Explanation

Each send delivers a value INTO the paused generator.

Constraints

  • Use the value of the yield expression.
  • Initial yield produces 0.

Topics

Iterators & Generatorssend

Companies

Jane StreetTwo SigmaGoogle

Hints

Hint 1

total += (yield total) inside a loop — mind the parentheses.

Hint 2

send resumes the generator with the sent value as the yield result.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.