Sliding Windows

Python for AIMedium+10 XP+10

Sliding Windows

To predict the next reading in a series, models are often trained on short windows: runs of neighbouring values.

Task: write a class Windows, created as Windows(values, size), that acts like a list of every window of size neighbouring values.

  • Window 0 is values[0:size], window 1 is values[1:size + 1], and so on. The last window ends at the last value.
  • len(w) is the number of full windows. If there are fewer values than size, it is 0.
  • w[i] gives window i as a list. Only indexes from 0 up are used.
  • Don't store the windows. Work each one out when it's asked for.
  • list(w) and for loops must work and must stop after the last window. For an index past the last window, raise an IndexError, just like a list does.

Examples

len(Windows([5, 6, 7, 8], 3))
returns 2
Windows([5, 6, 7, 8], 3)[1]
returns [6, 7, 8]

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run