Skip to content

Commit

Permalink
Merge pull request keon#16 from delirious-lettuce/moving_average
Browse files Browse the repository at this point in the history
'moving_average' fixes
  • Loading branch information
keon authored Apr 24, 2017
2 parents 0e566f4 + 7cc884e commit 8061b28
Showing 1 changed file with 12 additions and 15 deletions.
27 changes: 12 additions & 15 deletions queue/moving_average.py
Original file line number Diff line number Diff line change
@@ -1,32 +1,29 @@
from __future__ import division
from collections import deque


class MovingAverage(object):
def __init__(self, size):
"""
Initialize your data structure here.
:type size: int
"""
self.size = size
self.queue = collections.deque()
self.queue = deque(maxlen=size)

def next(self, val):
"""
:type val: int
:rtype: float
"""
self.queue.append(val)
if len(self.queue) > self.size:
self.queue.popleft()
sum = float(0)
for num in self.queue:
sum += num
return sum / len(self.queue)
return sum(self.queue) / len(self.queue)


# Given a stream of integers and a window size,
# calculate the moving average of all integers in the sliding window.

# For example,
m = MovingAverage(3);
m.next(1) = 1
m.next(10) = (1 + 10) / 2
m.next(3) = (1 + 10 + 3) / 3
m.next(5) = (10 + 3 + 5) / 3
if __name__ == '__main__':
m = MovingAverage(3)
assert m.next(1) == 1
assert m.next(10) == (1 + 10) / 2
assert m.next(3) == (1 + 10 + 3) / 3
assert m.next(5) == (10 + 3 + 5) / 3

0 comments on commit 8061b28

Please sign in to comment.