Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

All possible replacements of two lists?

I have two lists, both of the same length:

a = [1,2,3]
b = [4,5,6]

How can I get all possible results, from iterating over a and either choosing to replace it with the corresponding element from b, or not doing so?

output[0] = [1,2,3] # no replacements
output[1] = [4,2,3] # first item was replaced
output[2] = [1,5,3] # second item was replaced
output[3] = [1,2,6] # third item was replaced
output[4] = [4,5,3] # first and second items were replaced
output[5] = [4,2,6] # first and third items were replaced
output[6] = [1,5,6] # second and third items were replaced
output[7] = [4,5,6] # all items were replaced
like image 395
P. Shark Avatar asked Mar 09 '23 20:03

P. Shark


1 Answers

Creating 3 lists of two elements would not over-complicate the code at all. zip can "flip the axes" of multiple lists trivially (making X sequences of Y elements into Y sequences of X elements), making it easy to use itertools.product:

import itertools

a = [1,2,3]
b = [4,5,6]

# Unpacking result of zip(a, b) means you automatically pass
# (1, 4), (2, 5), (3, 6)
# as the arguments to itertools.product
output = list(itertools.product(*zip(a, b)))

print(*output, sep="\n")

Which outputs:

(1, 2, 3)
(1, 2, 6)
(1, 5, 3)
(1, 5, 6)
(4, 2, 3)
(4, 2, 6)
(4, 5, 3)
(4, 5, 6)

Different ordering than your example output, but it's the same set of possible replacements.

like image 75
ShadowRanger Avatar answered Mar 14 '23 18:03

ShadowRanger