Python: Compute the sum of elements of a given array of integers
11. Sum Elements Map
Write a Python program to compute the sum of elements of an array of integers. Use the map() function.
Sample Solution:
Python Code :
# Import the 'array' class from the 'array' module
from array import array
# Define a function 'array_sum' that takes an array of integers as input and returns the sum of its elements
def array_sum(nums_arr):
sum_n = 0
# Iterate through each element in 'nums_arr' and add it to 'sum_n'
for n in nums_arr:
sum_n += n
# Return the sum of the array elements
return sum_n
# Create an array 'nums' of type 'i' (signed integer) with the specified elements
nums = array('i', [1, 2, 3, 4, 5, -15])
# Print the original array 'nums'
print("Original array:", nums)
# Convert 'nums' to a list and store it in 'nums_arr'
nums_arr = list(map(int, nums))
# Call the 'array_sum' function with 'nums_arr' as the argument and store the result in 'result'
result = array_sum(nums_arr)
# Print the sum of all elements in the array
print("Sum of all elements of the said array:")
print(result)
Sample Output:
Original array: array('i', [1, 2, 3, 4, 5, -15]) Sum of all elements of the said array: 0
For more Practice: Solve these Related Problems:
- Write a Python program to use map to double each element in an array and then compute the sum of the doubled values.
- Write a Python program to square each element in an array using map and then calculate the total sum of the squares.
- Write a Python program to map a lambda that converts integers to floats and then compute their cumulative sum.
- Write a Python program to apply map to take the absolute value of each element in an array and then sum the results.
Go to:
Previous: Write a Python program to compute the square of first N Fibonacci numbers, using map function and generate a list of the numbers.
Next: Write a Python program to find the ration of positive numbers, negative numbers and zeroes in an array of integers.
Python Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.