Skip to content

Instantly share code, notes, and snippets.

@Whoeza
Created March 29, 2024 18:22
Show Gist options
  • Save Whoeza/9cb9a1b770bbb4ec3106f9fc71f898ce to your computer and use it in GitHub Desktop.
Save Whoeza/9cb9a1b770bbb4ec3106f9fc71f898ce to your computer and use it in GitHub Desktop.
[Python] Sliding window tutorial
# sliding_window_tutorial.py
# We have an array, a.k.a. a list.
my_array = [1, 2, 3, 4, 5,
6, 7, 8, 9, 10,
11, 12, 13, 14, 15,
16, 17, 18, 19, 20]
print("my_array: %s" % my_array)
print()
# my_array: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
# The idea: build the resulting array from taking one element out at a time.
# Cycle through all the elements, using 'range' and 'len'
for i in range(len(my_array)):
print("i=%s" % i)
# bottom: my_array[:i] means "all the elements up to the one of index i"
# e.g.
# i=0 i=1 i=2 ..etc..
# bottom_slice: [] bottom_slice: [1] bottom_slice: [1, 2] ..etc..
bottom_slice = my_array[:i]
# top: my_array[i+1:] means "all the elements starting from i+1"
top_slice = my_array[i + 1:]
# This combo skips the item of index i, in the current loop iteration.
# Time to build our "one-out array".
# Because '.extend' works in-place and returns 'None', I make a new
# array on which to operate. To do so, I use the generator syntax
# of Python: '[i for i in bottom_slice]'
# This will generate a list of items i from the items of bottom_slice.
# It's a way of writing a copy of another list.
one_out_array = [i for i in bottom_slice]
# '.extend' appends items, taking a list as input instead of the single item
# to append. So, I give a copy of 'top_slice' as input to '.extend'
one_out_array.extend([i for i in top_slice])
# So far, we have built our "one-out array".
# Save the "one-out element".
the_one_out = my_array[i]
# Print the result for your joy
print("bottom_slice: %s" % bottom_slice)
print("top_slice: %s" % top_slice)
print("one_out_array: %s" % one_out_array)
print("the_one_out: %s" % the_one_out)
# Print one extra line for extra space and go on for the next iteration
print()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment