Skip to content

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.

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 1A deque holds the current window; popleft() removes the oldest value.
Hint 2Add each new value to the sum and subtract the one that falls out of the window.
Hint 3Yield only once the window holds k values.

Learn the concepts

More Python problems

All Python problems