requirements
Given an integer data stream and a window size, calculate the moving average of all integers based on the size of the sliding window.
Implement the MovingAverage class:
MovingAverage(int size) initializes the object with the window size. Double Next (int val) computes and returns the moving average of the last size value in the data stream.
Example:
Input: [" MovingAverage ", "next", "next", "next", "next"] [[3], [1], [10], [3], [5]] output: [null, 1.0, 5.5, 4.66667, 6.0] explanation: MovingAverage movingAverage = new MovingAverage(3); movingAverage.next(1); // Return 1.0 = 1/1 movingAverage. Next (10); // Return 5.5 = (1 + 10) / 2 movingAverage. Next (3); // return 4.66667 = (1 + 10 + 3) / 3 movingAverage. Next (5); // Return 6.0 = (10 + 3 + 5) / 3Copy the code
Tip:
- 1 <= size <= 1000
- -105 <= val <= 105
- The next method is called up to 104 times
The core code
class MovingAverage:
def __init__(self, size: int) :
self.queue = deque()
self.Max_size = size
def next(self, val: int) - >float:
self.queue.append(val)
if len(self.queue) > self.Max_size:
self.queue.popleft()
return 1.0 * sum(self.queue) / len(self.queue)
# Your MovingAverage object will be instantiated and called as such:
# obj = MovingAverage(size)
# param_1 = obj.next(val)
Copy the code
For this problem, we are a data flow, so we choose to use two-way queue to solve this problem. If the number exceeds the maximum limit, the queue directly pops up, and then it is easy to get the average value of the data, that is, to construct a data structure, relatively simple.