CS 2104 interactive

Sliding window, traced

Watch a window of three days slide across a week of temperatures. Each step reuses almost all of the last step’s work, which is why the technique takes one pass through the data.

Interactive trace

CS 2104 · Problem Solving in Computer Science

    Before the loop runs

    Seven days, one window of three

    A week of temperatures. The window (k = 3) will slide forward one day at a time.

    1. enters leavesMon72
    2. enters leavesTue68
    3. enters leavesWed75
    4. enters leavesThu71
    5. enters leavesFri69
    6. enters leavesSat74
    7. enters leavesSun73
    1. window_sum = sum(data[:k])
    2. averages.append(window_sum / k)
    3. for i in range(k, len(data)):
    4. window_sum += data[i] - data[i-k]
    5. averages.append(window_sum / k)

    Tip: with the animation focused, the left and right arrow keys step through the slides.

    The same trace, as a table

    Five windows, one pass

    Sums and averages for each window of 3 days
    WindowDaysHow the sum is foundSumAverage
    1Mon to Wed72 + 68 + 7521571.7
    2Tue to Thu+ 71 (Thu) − 72 (Mon)21471.3
    3Wed to Fri+ 69 (Fri) − 68 (Tue)21571.7
    4Thu to Sat+ 74 (Sat) − 75 (Wed)21471.3
    5Fri to Sun+ 73 (Sun) − 71 (Thu)21672.0