Generate a list of strings with a sliding window using itertools, yield, and iter() in Python 2.7.1?

O.rka picture O.rka · Dec 6, 2011 · Viewed 9.7k times · Source

I'm trying to generate a sliding window function in Python. I figured out how to do it but not all inside the function. itertools, yield, and iter() are entirely new to me.

i want to input

a='abcdefg'
b=window(a,3)
print b
['abc','bcd','cde','def','efg']

the way i got it work was

def window(fseq, window_size=5):
    import itertools
    tentative=[]
    final=[]
    iteration=iter(fseq)
    value=tuple(itertools.islice(iteration,window_size))
    if len(value) == window_size:
        yield value
    for element in iteration:
        value = value[1:] + (element,)
        yield value

a='abcdefg'
result=window(a)
list1=[]
for k in result:
    list1.append(k)
list2=[]   
for j in list1:
    tentative=''.join(j)
    list2.append(tentative)
print list2

basically what im confused about is how to use the final value of the function inside the function?

here is my code for the function

def window(fseq, window_size=5):
    import itertools
    tentative=[]
    final=[]
    iteration=iter(fseq)
    value=tuple(itertools.islice(iteration,window_size))
    if len(value) == window_size:
        yield value
    for element in iteration:
        value = value[1:] + (element,)
        yield value
    for k in value:
        tentative.append(k)
    for j in tentative:
        tentative_string=''.join(j)
        final.append(tentative_string)
    return final



seq='abcdefg'
uence=window(seq)
print uence

i want it to return the joined list but when i press run it, it says "There's an error in your program * 'return' with argument inside generator"

I'm really confused . . .

Answer

Cédric Julien picture Cédric Julien · Dec 7, 2011

You mean you want to do this ? :

a='abcdefg'
b = [a[i:i+3] for i in xrange(len(a)-2)]
print b
['abc', 'bcd', 'cde', 'def', 'efg']