How to Create Combination of Element in Different Set?

256 views Asked by At

Let say that I have n lists and they are not disjoint. I want to make every combination of n elements which I get one from every lists I have but in that combination there are different elements and there are no double combination. So, [1,1,2] isn't allowed and [1,2,3] is same as [2,1,3].

For example, I have A=[1,2,3], B=[2,4,1], and C=[1,5,3]. So, the output that I want is [[1,2,5],[1,2,3],[1,4,5],[1,4,3],[2,4,1],[2,4,5],[2,4,3],[3,2,5],[3,4,5],[3,1,5]].

I have search google and I think function product in module itertools can do it. But, I have no idea how to make no same elements in every combinations and no double combinations.

2

There are 2 answers

10
Thomas Baruchel On BEST ANSWER

Maybe something like:

from itertools import product                                               
A=[1,2,3]
B=[2,4,1]
C=[1,5,3]
L = list(set([ tuple(sorted(l)) for l in product(A,B,C) if len(set(l))==3 ]))

Of course you would have to change 3 ot the relevant value if you work with more than 3 lists.

0
hiro protagonist On

how about this? create a dicitonary with the sorted permutations as key. accept values only if all the three integers are different:

from itertools import product
A=[1,2,3]
B=[2,4,1]
C=[1,5,3]

LEN = 3

dct = {tuple(sorted(item)): item for item in product(A,B,C) 
       if len(set(item)) == LEN}

print(dct)
vals = list(dct.values())
print(vals)