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.
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.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With