Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how code a function similar to itertools.product in python 2.5

Tags:

python

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.

like image 953
lgwest Avatar asked Nov 05 '09 15:11

lgwest


People also ask

How do you use the product function in Python?

prod() method in Python is used to calculate the product of all the elements present in the given iterable. Most of the built-in containers in Python like list, tuple are iterables. The iterable must contain numeric value else non-numeric types may be rejected. This method is new in Python version 3.8.

How do you show a product in Python?

Product() In the terms of Mathematics Cartesian Product of two sets is defined as the set of all ordered pairs (a, b) where a belongs to A and b belongs to B.

Why Itertool is used in Python?

Itertools is a module in Python, it is used to iterate over data structures that can be stepped over using a for-loop. Such data structures are also known as iterables. This module works as a fast, memory-efficient tool that is used either by themselves or in combination to form iterator algebra.


1 Answers

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)
like image 59
SilentGhost Avatar answered Sep 21 '22 12:09

SilentGhost