Streaming moving average

mediumPipelines~20 min · 8 tests

Latency dashboards, sensor feeds and training-loss curves all show a moving average. The values arrive one at a time and the stream may never end, so you can’t collect them first.

Write a generator moving_average(stream, window):

  • For each value from stream, yield the mean of the last window values seen so far, including this one.
  • Before window values have arrived, average whatever you have.
  • Be lazy. It must work on an infinite stream.
  • Each step should be O(1), not O(window).
  • window is at least 1.
>>> list(moving_average([2, 4, 6, 8], 2))
[2.0, 3.0, 5.0, 7.0]
Learn the ideaRead the lesson →
solution.pyPython 3.14 · Pyodide

Press ⌘ ↵ or Run to check the visible tests. Submit runs the hidden ones too. Everything runs in your browser.

⌘ ↵ to run