-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path0346.Moving_Average_from_Data_Stream.py
More file actions
48 lines (36 loc) Β· 1.32 KB
/
Copy path0346.Moving_Average_from_Data_Stream.py
File metadata and controls
48 lines (36 loc) Β· 1.32 KB
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
41
42
43
44
45
46
47
48
"""
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.
Example 1:
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) / 3
Constraints:
1 <= size <= 1000
-105 <= val <= 105
At most 104 calls will be made to next.
"""
class MovingAverage:
def __init__(self, size: int):
self.size = size
self.window = deque()
self.window_sum = 0
def next(self, val: int) -> float:
self.window.append(val)
self.window_sum += val
if len(self.window) > self.size:
self.window_sum -= self.window.popleft()
return self.window_sum / len(self.window)
# Your MovingAverage object will be instantiated and called as such:
# obj = MovingAverage(size)
# param_1 = obj.next(val)