CrossProductSweeper

Marcin 'Qrczak' Kowalczyk qrczak at knm.org.pl
Fri Sep 14 16:54:59 EDT 2001


10 Sep 2001 11:42:46 -0500, John Hunter <jdhunter at nitace.bsd.uchicago.edu> pisze:

> Here is a simple class to systematically investigate a cross product
> space, which you might normally do with a series nested for loops.
> I suspect that there is an existing way to do this, but sometimes its
> easier to roll your own that find the right package.  Please point
> me to the light if there is an existing way to do this I should be
> aware of.

Generators which are a recent feature of Python make it much easier.
Here is an example - works with Python-2.2a1:

from __future__ import generators

def cross_product(seqs):
    result = [None] * len(seqs)
    def level(i):
        if i == len(seqs):
            yield(tuple(result))
        else:
            for x in seqs[i]:
                result[i] = x
                for r in level(i+1): yield r
    for r in level(0): yield r

for x in cross_product(((1,2,3,4), (5,6), (7,8,9,10))):
    print x

Here is a nicer but less efficient implementation:

def cross_product(seqs):
    if seqs:
        for x in seqs[0]:
            for xs in cross_product(seqs[1:]):
                yield (x,) + xs
    else:
        yield ()

-- 
 __("<  Marcin Kowalczyk * qrczak at knm.org.pl http://qrczak.ids.net.pl/
 \__/
  ^^                      SYGNATURA ZASTĘPCZA
QRCZAK



More information about the Python-list mailing list