tags:

views:

200

answers:

2

I have a list of tuples, e.g:

A=[(1,2,3), (3,5,7,9), (7)]

and want to generate all permutations with one item from each tuple.

1,3,7
1,5,7
1,7,7
...
3,9,7

I can have any number of tuples and a tuple can have any number of elements. And I can't use itertools.product() because python 2.5.

+7  A: 

docs of itertools.product have an example of how to implement it in py2.5:

def product(*args, **kwds):
    # product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
    # product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
    pools = map(tuple, args) * kwds.get('repeat', 1)
    result = [[]]
    for pool in pools:
        result = [x+[y] for x in result for y in pool]
    for prod in result:
        yield tuple(prod)
SilentGhost
Aside from that `(*args, repeat=1)` doesn't work in Python 2.5...
ephemient
fixed that, I've accidentally copied the example from py3.1 docs.
SilentGhost
+3  A: 

The itertools documentation contains full code showing what each function is equivalent to. The product implementation is here.

Daniel Roseman
Thanks, I was to fast to ask I think.
lgwest