4-line Python Solution using deque


  • 18
    M
    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)

  • 7

    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)
    

  • 0
    A

    Stefan could you explain a bit on how the 'or' works?


  • 0

    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.


  • 0
    W
    This post is deleted!

  • 0
    W

    @StefanPochmann
    why q.append(v) is not true?
    isn't it one non-empty deque?


  • 6

    @liumingyu cool but your solution takes O(m) for next. You should achieve O(1) complexity.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.