-1

The following list is given [[1, 2, 3], [4, 2, 5, 6], [7, 2, 5], [8, 9, 10]]. How can I get all combinations of lists that hold all the combinations of the sublists? The order of the lists in the list does not matter. For example, here we have two of them: [[1, 3, 2], [4, 2, 5, 6], [7, 2, 5], [8, 9, 10]], [[2, 1, 3], [4, 2, 5, 6], [7, 2, 5], [8, 9, 10]] etc.

I have stumbled across very similar questions and suitable answers:

All combinations of a list of lists

How to get all possible combinations of a list’s elements?

But none of them solved this particular problem.

Eliahu Aaron
  • 4,103
  • 5
  • 27
  • 37
Aaron Scheib
  • 358
  • 4
  • 18

1 Answers1

2

How can I get all combinations of lists that hold all the combinations of the sublists? The order of the lists in the list does not matter. E.g. [[1, 3, 2], [4, 2, 5, 6], [7, 2, 5], [8, 9, 10]], [[2, 1, 3], [4, 2, 5, 6], [7, 2, 5], [8, 9, 10]]

You need to permute all inner lists and then product those. First store permutations of each inner lists in a 2D list (named all_perms in the code), then the product of those will be the required answer, for uniqueness, we need to store them in a set. Python's itertools.permutations gives all permutations and itertools.product gives all cartesian product among them. Here is the code:

from itertools import permutations as perm, product

# lists = [[1, 2, 3], [4, 2, 5, 6], [7, 2, 5], [8, 9, 10]]
lists = [[1,2],[3,4]] # let's check for a small input first
all_perms = [[] for _ in range(len(lists))]

for i, lst in enumerate(lists):
    all_perms[i].extend(list(perm(lst)))

answer = set()
prods = product(*all_perms)
for tup in prods:
    answer.add(tup)
print(answer)
# Output: {((1, 2), (4, 3)), ((2, 1), (3, 4)), ((2, 1), (4, 3)), ((1, 2), (3, 4))}

Feel free to ask for furthur queries.

LordOfThunder
  • 310
  • 1
  • 3
  • 17