forked from keon/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request keon#16 from delirious-lettuce/moving_average
'moving_average' fixes
- Loading branch information
Showing
1 changed file
with
12 additions
and
15 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |