python - 为什么我们在计算移动平均窗口时需要从右到左读取列表?
问题描述
我正在解决以下 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
从右到左读取,但是为什么在这个问题中这是必要的?当我去掉减号时,我得到了错误的答案,这是为什么呢?
解决方案
推荐阅读
- atom-editor - 无法在 Atom 编辑器中保存设置
- c - Arduino Uno:当第二次按下时,While-loop 无法“重新启动”使用按钮重置计时器?
- c# - VSCode 在单独的文件中找不到我的基本类
- python - 如何在 Visual Studio Code 中查找/执行 Python 交互模式?
- react-native - onEndReached 在渲染时被多次调用
- slack-api - 从 Slack API 中的“reaction_added”事件中获取“thread_ts”
- plotly - 在散点图中使用自定义字体图标
- paypal - 将 Paypal 支付按钮嵌入社区网站
- c++ - 如何在 SDL 中刷新屏幕(SDL_RenderClear 不起作用)?
- mysql - 为什么 MySQL 容器在使用 WSL 2 的 Windows 10 Home 上不断重启?