Iteration

François Pinard pinard at iro.umontreal.ca
Mon Aug 26 14:23:05 EDT 2002


[Jon Cosby]

> I want to extend this to any size, but I'm having problems with iteration.

Fun, I read your message just after having written a little tool able to
nest an arbitrary number of loops.  Maybe it could help?  Python 2.2 needed.

---------------------------------------------------------------------->
from __future__ import generators

# All generators below have the property of yielding successive results
# in sorted order, given than input sequences were already sorted.

def cartesian(*sequences):
    """\
Generate the "cartesian product" of all SEQUENCES.  Each yielded result
is a list containing an element taken from each original sequence.
"""
    if len(sequences) == 0:
        yield []
    else:
        first, remainder = sequences[0], sequences[1:]
        for element in first:
            for result in cartesian(*remainder):
                result.insert(0, element)
                yield result

# [reminder deleted]
----------------------------------------------------------------------<

For example, you could use it this way in your application:

   for indices in cartesian(*rows):
      ...

and then within the loop, `indices' holds [i, j, k, ...] as if you nested
as many loops as you have rows.  You get the idea.  I leave you with the
problem of generalising named indices into indexed indices. :-)

-- 
François Pinard   http://www.iro.umontreal.ca/~pinard




More information about the Python-list mailing list