Python – Dual element Rows Combinations
Sometimes, while working with data, we can have a problem in which we need to find combinations in list. This can be a simple. But sometimes, we need to perform a variation of it and have a dual element row instead of a single element. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using list comprehension + enumerate() The combination of above functions can be used to perform this task. In this, we iterate through the list and perform the combinations using comprehension and enumerate().
Python3
from collections import defaultdict
test_list = [[ 3 , 4 ], [ 5 , 6 ], [ 7 , 8 ]]
print ("The original list is : " + str (test_list))
res = [test_list[idx - len (test_list)] + test_list[idx + 1 - len (test_list)]
for idx, ele in enumerate (test_list)]
print ("Combination of dual rows list is : " + str (res))
|
Output :
The original list is : [[3, 4], [5, 6], [7, 8]]
Combination of dual rows list is : [[3, 4, 5, 6], [5, 6, 7, 8], [7, 8, 3, 4]]
Time complexity: O(M^N) as the number of combinations generated is M choose N.
Auxiliary space: O(M^N) as the size of the resultant list is also M choose N.
Method #2 : Using map() + lambda + combinations() The combinations of above functions can be used to perform this task. In this, the task of iteration and pairing is done by map() and combinations() respectively.
Python3
from itertools import combinations
test_list = [[ 3 , 4 ], [ 5 , 6 ], [ 7 , 8 ]]
print ("The original list is : " + str (test_list))
res = list ( map ( lambda ele: ele[ 0 ] + ele[ 1 ], combinations(test_list, 2 )))
print ("Combination of dual rows list is : " + str (res))
|
Output :
The original list is : [[3, 4], [5, 6], [7, 8]]
Combination of dual rows list is : [[3, 4, 5, 6], [5, 6, 7, 8], [7, 8, 3, 4]]
Last Updated :
15 Mar, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...