Moving Average from Data Stream

Problem: Moving Average from Data Stream

Use a queue to store the window. If the size of queue reaches limit, deque it.

Code in Python:

from collections import deque

class MovingAverage(object):

    def __init__(self, size):
        """
        Initialize your data structure here.
        :type size: int
        """
        self.window = deque([])
        self.size = size

    def next(self, val):
        """
        :type val: int
        :rtype: float
        """
        if len(self.window) >= self.size:
            self.window.popleft()
        self.window.append(val)
        return sum(self.window)*1.0/len(self.window)


# Your MovingAverage object will be instantiated and called as such:
# obj = MovingAverage(size)
# param_1 = obj.next(val)

results matching ""

    No results matching ""