Search code examples
pythonbioinformaticspython-itertoolssliding-window

Sliding Window with Variable Increment - Python


I am trying to use the sliding window function in Python to compare a very long list of values. The code I have found for the sliding window function is below:

from itertools import islice

idlist = [1, 2, 3, 4, 5, 6, 7, 8, 9]
list = []

def window(seq, n=2):
    "Returns a sliding window (of width n) over data from the iterable"
    "   s -> (s0,s1,...s[n-1]), (s1,s2,...,sn), ...                   "
    it = iter(seq)
    result = tuple(islice(it, n))
    if len(result) == n:
        yield result    
    for elem in it:
        result = result[1:] + (elem,)
        yield result

for i in window(idlist, n=2):
    list.append(i)

print list

My question is, how would I modify this code so I could change the increment of the window (the amount it moves after each tuple is generated) from 1 to a much greater integer, say 5 or 50? I know how to change the size of the window, but not the increment. Thanks!


Solution

  • You don't have to change the increment, you can take every n'th element:

    # taking every 3rd element moves the start by 3
    print list(islice(window(idlist, n=2),None,None,3))
    

    Not fully optimized, but simple.