Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing consecutive items when using a generator

Lets say I have a tuple generator, which I simulate as follows:

g = (x for x in (1,2,3,97,98,99))

For this specific generator, I wish to write a function to output the following:

(1,2,3)
(2,3,97)
(3,97,98)
(97,98,99)
(98,99)
(99)

So I'm iterating over three consecutive items at a time and printing them, except when I approach the end.

Should the first line in my function be:

t = tuple(g)

In other words, is it best to work on a tuple directly or might it be beneficial to work with a generator. If it is possible to approach this problem using both methods, please state the benefits and disadvantages for both approaches. Also, if it might be wise to use the generator approach, how might such a solution look?

Here's what I currently do:

def f(data, l):
    t = tuple(data)
    for j in range(len(t)):
        print(t[j:j+l])

data = (x for x in (1,2,3,4,5))
f(data,3)

UPDATE:

Note that I've updated my function to take a second argument specifying the length of the window.

like image 852
Baz Avatar asked Sep 20 '13 10:09

Baz


People also ask

What is difference between generator and iterator?

Iterators are the objects that use the next() method to get the next value of the sequence. A generator is a function that produces or yields a sequence of values using a yield statement. Classes are used to Implement the iterators. Functions are used to implement the generator.

What is the generator function?

Generator functions provide a powerful alternative: they allow you to define an iterative algorithm by writing a single function whose execution is not continuous. Generator functions are written using the function* syntax. When called, generator functions do not initially execute their code.

Which keyword is used to return a value from a generator?

The yield keyword in Python is similar to a return statement used for returning values in Python which returns a generator object to the one who calls the function which contains yield, instead of simply returning a value.


1 Answers

A specific example for returning three items could read

def yield3(gen):
    b, c = gen.next(), gen.next()
    try:
        while True:
            a, b, c = b, c, gen.next()
            yield (a, b, c)
    except StopIteration:
        yield (b, c)
        yield (c,)


g = (x for x in (1,2,3,97,98,99))
for l in yield3(g):
    print l
like image 150
David Zwicker Avatar answered Oct 12 '22 08:10

David Zwicker