[leetcode] 346. Moving Average from Data Stream @ python

版权声明:版权归个人所有,未经博主允许,禁止转载 https://blog.csdn.net/danspace1/article/details/87895737

原题

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

解法

双向队列 https://docs.python.org/3/library/collections.html#collections.deque

代码

class MovingAverage:

    def __init__(self, size: int):
        """
        Initialize your data structure here.
        """
        
        self.data = collections.deque(maxlen = size)       

    def next(self, val: int) -> float:        
        self.data.append(val)
        return sum(self.data)/len(self.data)

猜你喜欢

转载自blog.csdn.net/danspace1/article/details/87895737