File tree Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Original file line number Diff line number Diff line change
1
+ # -*- coding: utf-8 -*-
2
+ '''
3
+ Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window.
4
+
5
+ For example,
6
+ MovingAverage m = new MovingAverage(3);
7
+ m.next(1) = 1
8
+ m.next(10) = (1 + 10) / 2
9
+ m.next(3) = (1 + 10 + 3) / 3
10
+ m.next(5) = (10 + 3 + 5) / 3
11
+ '''
12
+ import collections
13
+ class MovingAverage (object ):
14
+ def __init__ (self , size ):
15
+ self .queue = collections .deque (maxlen = size )
16
+ """
17
+ Initialize your data structure here.
18
+ :type size: int
19
+ """
20
+
21
+
22
+ def next (self , val ):
23
+ queue = self .queue
24
+ queue .append (val )
25
+ return float (sum (queue ))/ len (queue )
26
+ """
27
+ :type val: int
28
+ :rtype: float
29
+ """
30
+
31
+
32
+
33
+ # Your MovingAverage object will be instantiated and called as such:
34
+ # obj = MovingAverage(size)
35
+ # param_1 = obj.next(val)
You can’t perform that action at this time.
0 commit comments