Question

I have a python 3 script that uses itertools.product, but I need to be able to run it on a machine that only has python 2.4 installed. Since itertools.product is new in python 2.6, I no longer have access to this function.

How can I emulate itertools.product in Python 2.4 in a pythonic way?

Was it helpful?

Solution

I'm not too familiar with python 2.4, but per the 2.7 docs:

This function is equivalent to the following code, except that the actual implementation does not build up intermediate results in memory:

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)

OTHER TIPS

Equivalent code from http://docs.python.org/library/itertools.html#itertools.product

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)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top