I have an original list in Python that look like this:
list = [a, 1, b, 2, c, 3]
I've split it into two lists as follows:
list_1 = [a, b, c]
list_2 = [1, 2, 3]
What I want to find is a final list of lists that gives me all the possible combinations of list_1
and list_2
without changing any letter or number from their current "column". So the output should look like that:
Desired output:
final_list =[[a, b, c],
[a, 2, c],
[a, b, 3],
[a, 2, 3],
[1, b, c],
[1, 2, c],
[1, b, 3],
[1, 2, 3]]
Any ideas how I might be able to achive this?
Here is a brute-force recursive approach:
def get_combinations(curr_list, list1, list2, index, overall_list):
if index == len(list1) or index == len(list2):
overall_list.append(curr_list[:])
return
curr_list[index] = list1[index]
get_combinations(curr_list, list1, list2, index+1, overall_list)
curr_list[index] = list2[index]
get_combinations(curr_list, list1, list2, index+1, overall_list)
list1 = list(input().strip().split())
list2 = list(input().strip().split())
overall_list = []
curr_list = [None] * min(len(list1), len(list2))
get_combinations(curr_list, list1, list2, 0, overall_list)
for l in overall_list:
print(*l)
Input:
a b c
1 2 3
Output:
a b c
a b 3
a 2 c
a 2 3
1 b c
1 b 3
1 2 c
1 2 3