Python – Odd or Even elements combinations Summations in Matrix

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.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of 
# Odd or Even elements combinations Summations in Matrix
# Using generator expression + lambda + sum() + map() + all()
from itertools import product
  
# initializing list
test_list = [[1, 5, 6], [7, 2, 4], [8, 9, 3]]
  
# printing original list
print("The original list is : " + str(test_list))
  
# Odd or Even elements combinations Summations in Matrix
# Using generator expression + lambda + sum() + map() + all()
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}
  
# printing result 
print("The all possible sums are : " + str(res)) 

chevron_right


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)}

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.