5/32
Part 2 of 6 · A fixed windowLearn and do

A window of fixed size

Now the two indexes walk in the same direction. Say the gateway counts requests per minute, and a dashboard wants the total over every 3 minutes in a row.

One step right: one entry enters and one leaves

def window_sums(values, k):
    total = sum(values[:k])
    sums = [total]
    for right in range(k, len(values)):
        # one enters, one leaves
        total += values[right] - values[right - k]
        sums.append(total)
    return sums

per_minute = [12, 7, 9, 15, 4, 11, 8]
print(window_sums(per_minute, 3))
Predict

Counts per minute: 12, 7, 9, 15, 4, 11, 8. The first 3-minute window totals 28. What does the second total?

Pick one to see what it prints.
Pick an answer above to see the rest
Predict

On 100,000 counts with k = 1,000, summing every slice took 531 ms. About how long does the running total take?

Pick an answer above to see the rest