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.
Implement a class MovingAverage: MovingAverage(size) sets the window size, and next(val) adds val to the stream and returns the current moving average as a float (the average of all values seen so far while fewer than size have arrived). The tests print each returned value to 2 decimal places.
Example
3 1,10,3,5
1.00 5.50 4.67 6.00
- Input: the window size (the
sizeargument), then the stream1, 10, 3, 5, one value at a time. After each arrival, the average covers only the most recent values, at most of them. - Value 1: only one value seen so far, so the window is and the average is .
- Value 10: the window is , still shorter than , so divide by 2: .
- Value 3: the window is now full, : , shown as 4.67.
- Value 5: a fourth value exceeds , so the oldest value, 1, leaves the window. It becomes and the average is .
- Output: one average per arrival,
1.00,5.50,4.67,6.00, each shown to 2 decimal places. Notice the divisor grows 1, 2, 3 and then stays at : before the window fills, you divide by how many values have arrived, not by .
Constraints
- 1 <= k <= 1000
- -10^5 <= val <= 10^5
- At most 10^4 calls to next