List Combinations

Arnaud Delobelle arnodel at googlemail.com
Wed Mar 12 18:55:18 EDT 2008


On Mar 12, 3:38 pm, "Reedick, Andrew" <jr9... at ATT.COM> wrote:
[...]
> Start here
>
> http://www.mail-archive.com/python-l...@python.org/msg178356.html
> 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
        else:
            for vals[i] in iters[i]:
                i += 1
                break
            else:
                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 :)

--
Arnaud




More information about the Python-list mailing list