Python – Odd or Even elements combinations Summations in Matrix
Last Updated :
08 Mar, 2023
Sometimes, while working with Python, we can have problems in which we need to extract all possible summations of elements, one from each row in matrix, either all odd or even elements. This is quite peculiar problem, but can have applications in certain domains. Lets discuss certain way in which this task can be performed. Method : Using generator expression + lambda + sum() + map() + all() The combination of above methods can be used to perform this task. In this, we perform the task of extraction of pairs, all odd or even using all() + generator expression. The task of construction of summations is done using sum() and lambda function.
Python3
from itertools import product
test_list = [[ 1 , 5 , 6 ], [ 7 , 2 , 4 ], [ 8 , 9 , 3 ]]
print ("The original list is : " + str (test_list))
temp1 = product( * test_list)
temp2 = (sub for sub in temp1 if all (ele % 2 = = 0 for ele in sub)
or all (ele % 2 = = 1 for ele in sub))
res = { sum ( map ( lambda idx : idx, ele)) : ele for ele in temp2}
print ("The all possible sums are : " + str (res))
|
Output :
The original list is : [[1, 5, 6], [7, 2, 4], [8, 9, 3]] The all possible sums are : {16: (6, 2, 8), 17: (1, 7, 9), 18: (6, 4, 8), 21: (5, 7, 9), 11: (1, 7, 3), 15: (5, 7, 3)}
Time Complexity: O(n*n) where n is the total number of values in the list “test_list”.
Auxiliary Space: O(n) where n is the total number of values in the list “test_list”.
Share your thoughts in the comments
Please Login to comment...