I am solving the following Leetcode design question: https://leetcode.com/problems/moving-average-from-data-stream/
Here is an accepted solution:
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)
I understand it all, except for the window_sum = sum(queue[-size:])
; in particular, what does queue[-size:]
do? I know it reads the list queue
from right to left, but why is this necessary in this question? And when I take the minus sign away I get the wrong answer, why is this?