Array Statistics
Problem Statement
Calculate basic statistics of a NumPy array.
Background
NumPy provides statistical functions:
- np.sum(): Sum of elements
- np.mean(): Average
- np.min(), np.max(): Min and max
- np.std(): Standard deviation
Your Task
Write a function array_stats(arr) that returns a dictionary with:
- "sum": Sum of all elements
- "mean": Mean (average), rounded to 2 decimals
- "min": Minimum value
- "max": Maximum value
- "std": Standard deviation, rounded to 2 decimals
Output Format
Return a dictionary with exactly these five keys.
Example:
[1, 2, 3, 4, 5]
{'sum': 15, 'mean': 3.0, 'min': 1, 'max': 5, 'std': 1.41}sum=15, mean=3, min=1, max=5, std≈1.41
Constraints:
- Round mean and std to 2 decimal places
- Array will have at least 1 element
1. Background Knowledge
NumPy arrays are the standard for efficient numerical computation in Python, enabling vectorized operations that avoid Python loops for high performance. Key statistical functions are built-in:
- Sum: ∑i=1n​xi​
- Mean: μ=\frac{1}{n}\sum_{i=1}nxi​
- Min/Max: \min(x) = x_{\text{min}}, \max(x) = x_{\text{max}}
- Standard Deviation: \sigma = \sqrt{\frac{1}{n}\sum_{i=1}n(xi​−\mu)^2} (population std by default in np.std)
Prerequisites: Basic NumPy array creation (np.array()), dictionary usage, and rounding (round(value, 2)).
2. Algorithm Approach
Use NumPy's optimized C-implemented functions for O(n) linear scans across the array—no custom loops needed. This leverages array programming paradigm: single function calls compute statistics via vectorization, minimizing operation counts and memory copies.
Direct mapping:
| Statistic | NumPy Function |
|---|---|
| sum | np.sum(arr) |
| mean | np.mean(arr) |
| min | np.min(arr) |
| max | np.max(arr) |
| std | np.std(arr) |
3. Step-by-Step Strategy
- Import NumPy: import numpy as np
- Define function: def array_stats(arr):
- Compute statistics using built-in functions
- Round mean/std: round(np.mean(arr), 2) and round(np.std(arr), 2)
- Return dictionary: return {"sum":..., "mean":..., "min":..., "max":..., "std":...}
Continue the full explanation
You're reading the free preview. Unlock the complete walkthrough, the code editor, test runner and reference solution with Premium.
Editor locked
The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.