![]() |
VOOZH | about |
Given an array of integers, find the sum of its elements. For Examples:
Input: [1, 2, 3]
Output: 6
Explanation: 1 + 2 + 3 = 6
Let's explore different methods to find the sum of an array one by one:
Python provides a built-in sum() function to calculate the sum of elements in a list, tuple or set.
Sum: 34
The reduce() function from functools applies a function cumulatively to the elements of an iterable, effectively summing all elements.
Sum: 34
Explanation: reduce() applies a function cumulatively to items of the iterable, combining them into a single result (here it repeatedly adds pairs).
Iterating through the array and adding each element to the sum variable and finally displaying the sum.
Sum: 34
enumerate() allows looping through an array with an index and element. This method adds each element to a running sum.
34
Explanation: for i, val in enumerate(arr) loop over arr while also receiving the index i (0, 1, 2, ...) and the element val.
Please refer complete article on Program to find sum of elements in a given array for more details!