Home > Net >  Find all combinations of tuples inside of a list
Find all combinations of tuples inside of a list

Time:08-26

I am trying to find all permutations of the items inside of the tuples while in the list of length 2. The order of the tuples in relation to each other does not matter.

perm = [(3, 6), (6, 8), (4, 1), (7, 4), (5, 3),
        (1, 9), (2, 5), (4, 8), (5, 1), (3, 7),
        (6, 9), (10, 2), (7, 10), (8, 2), (9, 10)]

An example of one permutation of the above list would be:

perm = [(6, 3), (6, 8), (4, 1), (7, 4), (5, 3),
        (1, 9), (2, 5), (4, 8), (5, 1), (3, 7),
        (6, 9), (10, 2), (7, 10), (8, 2), (9, 10)]

Another example permutation would be:

perm = [(6, 3), (8, 6), (1, 4), (4, 7), (3, 5),
        (9, 1), (5, 2), (8, 4), (1, 5), (7, 3),
        (9, 6), (2, 10), (10, 7), (2, 8), (10, 9)]

In the end, the length of the list of permutations should be 32768, because each tuple is either swapped or not swapped, and 2^15 = 32768. I do not care about the order of the tuples in relation to each other, only the permutations of the items inside of the tuples.

I have tried to use itertools permute, combinations, and product, but I haven't been able to get the desired result.

CodePudding user response:

You can use product:

from itertools import product

lst = [(3, 6), (6, 8), (4, 1), (7, 4), (5, 3),
       (1, 9), (2, 5), (4, 8), (5, 1), (3, 7),
       (6, 9), (10, 2), (7, 10), (8, 2), (9, 10)]

output = product(*([(x, y), (y, x)] for x, y in lst))

output = list(output) # if you want a list, rather than a generator

print(len(output))
# 32768

print(output[0])
# ((3, 6), (6, 8), (4, 1), (7, 4), (5, 3), (1, 9), (2, 5), (4, 8), (5, 1), (3, 7), (6, 9), (10, 2), (7, 10), (8, 2), (9, 10))
print(output[-1])
# ((6, 3), (8, 6), (1, 4), (4, 7), (3, 5), (9, 1), (5, 2), (8, 4), (1, 5), (7, 3), (9, 6), (2, 10), (10, 7), (2, 8), (10, 9))

The key is to write something like

output = product([(3,6), (6,3)], [(6,8), (8,6)], ..., [(9,10), (10,9)])

in a generic way so that any input list would work, which is done by the generator expression and unpacking (*).

  • Related