need help on generator...

Craig Ringer craig at postnewspapers.com.au
Fri Jan 21 09:38:10 EST 2005


On Fri, 2005-01-21 at 17:14 +0300, Denis S. Otkidach wrote:
> On 21 Jan 2005 05:58:03 -0800
> joh12005 at yahoo.fr (Joh) wrote:
> 
> > i'm trying to understand how i could build following consecutive sets
> > from a root one using generator :
> > 
> > l = [1,2,3,4]
> > 
> > would like to produce :
> > 
> > [1,2], [2,3], [3,4], [1,2,3], [2,3,4] 
> 
> >>> def consecutive_sets(l):
> ...     for i in xrange(2, len(l)):
> ...         for j in xrange(0, len(l)-i+1):
> ...             yield l[j:j+i]

Since you have a much faster brain than I (though I ended up with
exactly the same thing barring variable names) and beat me to posting
the answer, I'll post the inevitable awful generator expression version
instead:

consecutive_sets = ( x[offset:offset+subset_size]
                     for subset_size in xrange(2, len(x))
                     for offset in xrange(0, len(x) + 1 - subset_size) )

--
Craig Ringer




More information about the Python-list mailing list