Skip to content

Instantly share code, notes, and snippets.

@kuntalchandra
Created September 8, 2020 12:50
Show Gist options
  • Save kuntalchandra/a97c53bc38942e7a843460041851c67e to your computer and use it in GitHub Desktop.
Save kuntalchandra/a97c53bc38942e7a843460041851c67e to your computer and use it in GitHub Desktop.
Moving Average from Data Stream
"""
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