two generators working in tandem

Anton Vredegoor anton.vredegoor at gmail.com
Sun Feb 12 07:56:18 EST 2006


Michael Spencer wrote:

> This returns an iterator that 'nests' an arbitrary number of sequences
> (odometer-style).
>
> def nest(*sequences):
>      def _nest(outer, inner):
>          for outer_item in outer:
>              if not isinstance(outer_item, tuple):
>                  outer_item = (outer_item,)
>              for inner_item in inner:
>                  yield outer_item + (inner_item,)
>      return reduce(_nest, sequences)

Nice!

Here's a nonrecursive version. It creates a list of iterators that are
repeating their values just enough times to sychronize the nesting. I
wonder if 'ncycle' would be a useful generalization for itertools'
'cycle' function.

Anton

def ncycle(seq,n):
    while True:
        for x in seq:
            for dummy in xrange(n):
                yield x

def cross(*args):
    p = 1
    R = []
    for arg in args[::-1]:
        L = list(arg)
        R.append(ncycle(L,p))
        p *= len(L)
    R.reverse()
    for dummy in xrange(p):
        yield [x.next() for x in R]

def test():
    s1='a1','a2','a3','a4'
    s2='b1','b2'
    s3='c1','c2','c3'
    for x in cross(s1,s2,s3):
        print x

if __name__=='__main__':
    test()




More information about the Python-list mailing list