24. Moving Average over a Stream
Difficulty: Medium · Topic: Generators & iterators
Write a generator moving_average(values, k): for every window of k consecutive values, yield its average, starting with the first full window.
- Work in constant time per value: keep a running sum instead of re-adding the window.
- The input can be endless.
kbelow 1 raisesValueError.
Your code runs in CPython on our servers against 6 tests, including hidden ones.
Sample test
list(moving_average([1, 2, 3, 4, 5], 2))Expected: [1.5, 2.5, 3.5, 4.5]
Hints
Hint 1
Adeque holds the current window; popleft() removes the oldest value.Hint 2
Add each new value to the sum and subtract the one that falls out of the window.Hint 3
Yield only once the window holdsk values.Learn the concepts
- Generators and lazy evaluation · 6 min read. yield, constant-memory pipelines, endless inputs and the one-pass rule.
More Python problems
- Read a File in Chunks · Easy
- Batch an Iterable · Easy
- A Generator Pipeline · Medium
- Flatten Any Iterable Lazily · Medium
- A Re-iterable Date Range · Medium
- Merge Sorted Streams Lazily · Hard