Python – All replacement combination from other list
Given a list, the task is to write a Python program to perform all possible replacements from other lists to the current list.
Input : test_list = [4, 1, 5], repl_list = [8, 10]
Output : [(4, 1, 5), (4, 1, 8), (4, 1, 10), (4, 5, 8), (4, 5, 10), (4, 8, 10), (1, 5, 8), (1, 5, 10), (1, 8, 10), (5, 8, 10)]
Explanation : All elements are replaced by 0 or more elements from 2nd list
Input : test_list = [4, 1], repl_list = [8, 10]
Output : [(4, 1), (4, 8), (4, 10), (1, 8), (1, 10), (8, 10)]
Explanation : All elements are replaced by 0 or more elements from 2nd list
Method #1 : Using combinations() + len()
In this, we perform the task of constructing combinations of the merged lists using combinations() and len() is used to restrict the size of output to the length of the initial list.
Python3
from itertools import combinations
test_list = [ 4 , 1 , 5 ]
print ( "The original list is : " + str (test_list))
repl_list = [ 8 , 10 ]
res = list (combinations(test_list + repl_list, len (test_list)))
print ( "All combinations replacements from other list : " + str (res))
|
Output:
The original list is : [4, 1, 5] All combinations replacements from other list : [(4, 1, 5), (4, 1, 8), (4, 1, 10), (4, 5, 8), (4, 5, 10), (4, 8, 10), (1, 5, 8), (1, 5, 10), (1, 8, 10), (5, 8, 10)]
Time Complexity: O(n)
Auxiliary Space: O(1)
Method #2 : Using combinations() + extend()
In this, we perform the task of concatenating the list using extend(), rest all the functionalities is similar to the above method.
Python3
from itertools import combinations
test_list = [ 4 , 1 , 5 ]
print ( "The original list is : " + str (test_list))
repl_list = [ 8 , 10 ]
n = len (test_list)
test_list.extend(repl_list)
res = list (combinations(test_list, n))
print ( "All combinations replacements from other list : " + str (res))
|
Output:
The original list is : [4, 1, 5] All combinations replacements from other list : [(4, 1, 5), (4, 1, 8), (4, 1, 10), (4, 5, 8), (4, 5, 10), (4, 8, 10), (1, 5, 8), (1, 5, 10), (1, 8, 10), (5, 8, 10)]
Time Complexity: O(n), where n is the number of elements in the list “test_list”.
Auxiliary Space: O(n), where n is the number of elements in the list “test_list”.
Last Updated :
10 Mar, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...