import collections class MovingAverage(object): def __init__(self, size): """ Initialize your data structure here. :type size: int """ self.queue = collections.deque(maxlen=size) def next(self, val): """ :type val: int :rtype: float """ queue = self.queue queue.append(val) return float(sum(queue))/len(queue) # Your MovingAverage object will be instantiated and called as such: # obj = MovingAverage(size) # param_1 = obj.next(val)
Very nice. I didn't know the maxlen parameter, thanks. Even allows a one-liner:
class MovingAverage(object): def __init__(self, size): self.next = lambda v, q=collections.deque((), size): q.append(v) or 1.*sum(q)/len(q)
x or y is
x if it's true, else
y. So it does
q.append(v), which isn't true, and then returns
1.*sum(q)/len(q). Just a little trick to do those two things in one expression.
why q.append(v) is not true?
isn't it one non-empty deque?
Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.