首页 > 解决方案 > 为什么我们在计算移动平均窗口时需要从右到左读取列表?

问题描述

我正在解决以下 Leetcode 设计问题:https ://leetcode.com/problems/moving-average-from-data-stream/

这是一个公认的解决方案:

class MovingAverage:
    def __init__(self, size: int):
        self.size = size
        self.queue = []

    def next(self, val: int) -> float:
        size, queue = self.size, self.queue
        queue.append(val)
        # calculate the sum of the moving window
        window_sum = sum(queue[-size:])

        return window_sum / min(len(queue), size)

我都明白了,除了window_sum = sum(queue[-size:]); 特别是queue[-size:]做什么?我知道它list queue从右到左读取,但是为什么在这个问题中这是必要的?当我去掉减号时,我得到了错误的答案,这是为什么呢?

标签: python

解决方案


推荐阅读