-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy path346-Moving-Average-from-Data-Stream.py
40 lines (30 loc) · 1.13 KB
/
346-Moving-Average-from-Data-Stream.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
'''
Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window.
Implement the MovingAverage class:
MovingAverage(int size) Initializes the object with the size of the window size.
double next(int val) Returns the moving average of the last size values of the stream.
'''
class MovingAverage:
def __init__(self, size: int):
self.queue = []
self.movingAvg = 0
self.size = size
self.count = 0
self.total = 0
def next(self, val: int) -> float:
if(len(self.queue) < self.size):
self.queue.append(val)
self.count += 1
self.total += val
self.movingAvg = (self.total) / self.count
return self.movingAvg
else:
self.total -= self.queue[0]
self.queue.pop(0)
self.queue.append(val)
self.total += val
self.movingAvg = (self.total) / self.size
return self.movingAvg
# Your MovingAverage object will be instantiated and called as such:
# obj = MovingAverage(size)
# param_1 = obj.next(val)