Search code examples
pythoncombinationspermutationpython-itertoolscartesian-product

How can I dynamic get combination/permutation of groups in python?


I have 3 groups

[1,2] [4,5] [a,b]

I want the permutations/combinations of these like this

1  4  a
1  5  a
1  4  b
1  5  b
2  4  a    
2  5  a
2  4  b
2  5  b
12 4  a
12 5  a
12 4  b
12 5  b
12 4  ab
12 5  ab
1  45 a
2  45 a
1  45 b
2  45 b
1  45 ab
2  45 ab
1  4  ab
2  5  ab
12 45 ab

This arrays can grow and won't alway be the same size, so the permutation will increase.

I got this so far.

from itertools import *

bag1 = [1, 2]
bag2 = [4, 5]
bag3  = ['a', 'b']

bags = []

bags.append(bag1)
bags.append(bag2)
bags.append(bag3)

comb = list(product(*bags))

Solution

  • Given your piece of code, you need to use the cartesian product (product), on all the possible combinations of your starting 'bags':

    from itertools import product, combinations
    
    def comb_bag(bag):
        new_bag = []
        for n in range(1, 1+len(bag)):
            new_bag += list(combinations(bag, n))
    
        return new_bag
    
    bag1 = [1, 2]
    bag2 = [4, 5]
    bag3 = ['a', 'b']
    
    comb = list(product(comb_bag(bag1), comb_bag(bag2), comb_bag(bag3)))
    
    for e in comb:
        print(e)