Created
September 8, 2020 12:50
-
-
Save kuntalchandra/a97c53bc38942e7a843460041851c67e to your computer and use it in GitHub Desktop.
Moving Average from Data Stream
This file contains hidden or 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
""" | |
Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window. | |
Example: | |
MovingAverage m = new 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 | |
""" | |
from collections import deque | |
class MovingAverage: | |
def __init__(self, size: int): | |
self.q = deque() | |
self.cap = size | |
def next(self, val: int) -> float: | |
if len(self.q) == self.cap: | |
self.q.popleft() | |
self.q.append(val) | |
return sum(self.q) / len(self.q) | |
# Your MovingAverage object will be instantiated and called as such: | |
# obj = MovingAverage(size) | |
# param_1 = obj.next(val) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment