8000 added movingAverage.py · 0ff5ec/Programming@971c8ab · GitHub
[go: up one dir, main page]

Skip to content

Commit 971c8ab

Browse files
committed
added movingAverage.py
1 parent d6d2972 commit 971c8ab

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

movingAverage.py

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
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)

0 commit comments

Comments
 (0)
0