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)
网友评论