1

I want to replace a list of items with another list in all the possible combinations without any repetitions, For example

list1 =[1,2,3] 

list2 = [4,5]
Output =
[1,2,3],
[1,2,4],
[1,2,5],
[1,4,3],
[1,5,3],
[4,2,3],
[5,2,3],
[1,4,5],
[4,2,5],
[4,5,3]

I have tried itertools.product with zip but the result is not really what I wanted, I am wondering if anyone has any idea how to do this, I really appreciate your help. :)

Monica
  • 51
  • 5
  • 1
    @Adamantoisetortoise I assume their question is *how* to generate the output from the input. – Masklinn Oct 28 '20 at 11:12
  • @hiroprotagonist don't think this can generate the last few items e.g. have `4` come first in the output sequence. – Masklinn Oct 28 '20 at 11:15

2 Answers2

0

OP keeps the order of list1, and masks it with elements from list2. I create a powerset of list2, and extend it with Nones to match the length of list1 (= helper). Then I iterate over unique permutations of helper, masking one array with the other to hide parts of list1 where the mask contains a not-None value.

Powerset from: How to get all subsets of a set? (powerset)

from itertools import chain, combinations, permutations


def powerset(iterable):
    "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
    s = list(iterable)
    return chain.from_iterable(combinations(s, r) for r in range(len(s) + 1))


list1 = [1, 2, 3]

list2 = [4, 5]

solutions = []
for s in powerset(list2):
    # for every possibility of list2
    helper = [None] * (len(list1) - len(s))
    helper.extend(s)
    # create something like [None, None, 4]
    for perm in set(permutations(helper, len(helper))):
        # for each permutation of the helper, mask out nones
        solution = []
        for listchar, helperchar in zip(list1, perm):
            if helperchar != None:
                solution.append(helperchar)
            else:
                solution.append(listchar)
        solutions.append(solution)

print(solutions)
# [[1, 2, 3], [4, 2, 3], [1, 4, 3], [1, 2, 4], [1, 2, 5], [5, 2, 3], [1, 5, 3], [1, 5, 4], [4, 2, 5], [5, 2, 4], [5, 4, 3], [1, 4, 5], [4, 5, 3]]
-1

Here is a solution:

from itertools import combinations

output = list(combinations(list1 + list2, 3))
Riccardo Bucco
  • 13,980
  • 4
  • 22
  • 50