List Combinations

Arnaud Delobelle arnodel at
Wed Mar 12 23:55:18 CET 2008

On Mar 12, 3:38 pm, "Reedick, Andrew" <jr9... at ATT.COM> wrote:
> Start here
> and go through the thread.  There are several ways to solve the problem
> and we evaluated the performance and 'pythonicity' of each.  

I used a kind of extended cartesian product function a while ago while
writing a parser.  If I simplify it down to a simple product function
it goes like this:

def product(*sequences):
    i, n = 0, len(sequences)
    vals = [None]*n
    iters = map(iter, sequences)
    while i >= 0:
        if i == n:
            yield tuple(vals)
            i -= 1
            for vals[i] in iters[i]:
                i += 1
                iters[i] = iter(sequences[i])
                i -= 1

It's neither recursive nor a hack, I haven't tried to measure it
against other approaches (obviously it wouldn't beat the eval(...)
hack).  I haven't optimised it for readability (by others) either :)


More information about the Python-list mailing list