w3resource

Python: Compute the sum of elements of a given array of integers

Python map: Exercise-11 with Solution

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

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

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.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/python-exercises/map/python-map-exercise-11.php