Given a 2-D matrix, we need to find sum of all elements present in matrix ? Examples:
Input : arr = [[1, 2, 3],
[4, 5, 6],
[2, 1, 2]]
Output : Sum = 26
This problem can be solved easily using two for loops by iterating whole matrix but we can solve this problem quickly in python using map() function.
Python3
def findSum(arr):
return sum(map(sum,arr))
if __name__ == "__main__":
arr = [[1, 2, 3], [4, 5, 6], [2, 1, 2]]
print ("Sum = ",findSum(arr))
|
What does map() do?
The map() function applies a given function to each item of an iterable(list, tuple etc.) and returns a list of the results. For example see given below example :
Python3
def calculateSquare(n):
return n*n
numbers = [1, 2, 3, 4]
result = map(calculateSquare, numbers)
print (result)
set_result=list(result)
print(set_result)
|
Output<map object at 0x7fdf95d2a6d8>
[1, 4, 9, 16]
Last Updated :
21 Jul, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...