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.
- enters leavesMon72
- enters leavesTue68
- enters leavesWed75
- enters leavesThu71
- enters leavesFri69
- enters leavesSat74
- enters leavesSun73
- window_sum = sum(data[:k])
- averages.append(window_sum / k)
- for i in range(k, len(data)):
- window_sum += data[i] - data[i-k]
- 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
| Window | Days | How the sum is found | Sum | Average |
|---|---|---|---|---|
| 1 | Mon to Wed | 72 + 68 + 75 | 215 | 71.7 |
| 2 | Tue to Thu | + 71 (Thu) − 72 (Mon) | 214 | 71.3 |
| 3 | Wed to Fri | + 69 (Fri) − 68 (Tue) | 215 | 71.7 |
| 4 | Thu to Sat | + 74 (Sat) − 75 (Wed) | 214 | 71.3 |
| 5 | Fri to Sun | + 73 (Sun) − 71 (Thu) | 216 | 72.0 |