Streaming Running Average

Medium ⏱ 12 min 63% acceptance ★★★★☆ 4.4
Write the generator running_avg(stream) that consumes numbers and yields the average of everything seen so far after each one — one pass, O(1) state (count and total), no storing the history.

Examples

Example 1
Input
list(running_avg([10, 20, 60]))
Output
[10.0, 15.0, 30.0]
Explanation

Averages after each arrival.

Constraints

  • Single pass.
  • Only count and total as state.

Topics

Iterators & Generatorsstateful stream

Companies

BloombergTwo SigmaMorgan Stanley

Hints

Hint 1

total += x; count += 1; yield total / count.

Hint 2

No lists.

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