Array Sum - Python Basics for ML
Implement Array Sum in Python with NumPy. easy exercise with examples, hints, and instant feedback. No setup or signup required.
Array Sum
What you'll build
A function array_sum(arr) that returns the sum of every element of a NumPy array, using one vectorised call instead of a Python loop.
Background
Summing is the simplest reduction, and the one hiding inside most ML code: a mean loss is a sum divided by the batch size, a dot product is a sum of products, and a softmax denominator is a sum of exponentials. np.sum runs a compiled loop over contiguous memory, so it is typically about 100x faster than a Python for loop on large arrays.
Formula
array_sum(arr) = arr[0] + arr[1] + ... + arr[n-1] (over every element, whatever the shape)
Inputs
arr: NumPy array of numbers (integers or floats) with1 <= arr.size <= 1000and values in[-10^6, 10^6]. Usually 1D, but sum every element if it has more dimensions.
Expected Return Format
A single number: the total. It may be a NumPy scalar (np.int64 for integer input, np.float64 for float input); the tests compare its value.
Constraints
Use NumPy (np.sum or arr.sum()); no Python loops.
Follow-up
- How would you sum each row of a 2D array instead? Each column?
- Summing many float32 values can lose precision. Why does NumPy's pairwise summation help?
Examples
Input: array_sum(np.array([1, 2, 3, 4, 5])) Output: 15
1 + 2 + 3 + 4 + 5 = 15
Input: array_sum(np.array([-1, 0, 1])) Output: 0
Negative and positive values cancel: -1 + 0 + 1 = 0
Input: array_sum(np.array([0.5, 1.5, -1.0])) Output: 1.0
Float input gives a float total.
Practice in Python
import numpy as np
def array_sum(arr: np.ndarray) -> float:
"""
Calculate the sum of all elements in a NumPy array.
Args:
arr: NumPy array of numbers (any shape, at least one element)
Returns:
The sum of all elements, as a number (a NumPy scalar is fine)
"""
# Your code here
pass
The interactive editor loads with Python and NumPy. Run your implementation against 6 tests, or use the progressive hints.