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]
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
21 Jul, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...