美文网首页
[10.16 Easy] 346. Moving Average

[10.16 Easy] 346. Moving Average

作者: Mree111 | 来源:发表于2019-10-18 10:48 被阅读0次

    Description

    给定序列和window,输出moving average
    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

    Solution

    class MovingAverage(object):
    
        def __init__(self, size):
            """
            Initialize your data structure here.
            :type size: int
            """
            self.size = size
            self.list = []
            self.cnt = 0
            self.sum = 0
        def next(self, val):
            """
            :type val: int
            :rtype: float
            """
            if self.cnt < self.size:
                self.list.append(val)
                self.sum += val
            else:
                head = self.list.pop(0)
                self.sum -= head
                self.list.append(val)
                self.sum += val
                self.cnt -=1
            
            self.cnt+=1
            return  1.0*self.sum / self.cnt
        
    # Your MovingAverage object will be instantiated and called as such:
    # obj = MovingAverage(size)
    # param_1 = obj.next(val)
    

    相关文章

      网友评论

          本文标题:[10.16 Easy] 346. Moving Average

          本文链接:https://www.haomeiwen.com/subject/vbfimctx.html