📘
Moving Average from Data Stream
Given a stream of integers and a window size k, calculate the moving average of the last k values each time a new value arrives.
You will receive the window size and a sequence of values. For each value, output the moving average with 2 decimal places.
Example:
Input:
3 1,10,3,5
Output:
1.00 5.50 4.67 6.00
Reasoning:
- Initially, the window size
kis set to 3, and the first value 1 arrives, so the moving average is 1.00=11. - When the second value 10 arrives, the window contains [1, 10], so the moving average is 21+10=5.50.
- The third value 3 arrives, and the window becomes [1, 10, 3], so the moving average is 31+10+3=4.67.
- Finally, the fourth value 5 arrives, and the window updates to [10, 3, 5], so the moving average is 310+3+5=6.00.
Constraints:
- 1 <= k <= 1000
- -10^5 <= val <= 10^5
- At most 10^4 calls to next
Editor
Python 3.13.1
Test Results
0/0Run code to see test results.