Basic Array Arithmetic
Problem Statement
Perform basic arithmetic operations on NumPy arrays.
Background
NumPy supports element-wise arithmetic:
- arr + n: Add n to each element
- arr - n: Subtract n from each element
- arr * n: Multiply each element by n
- arr / n: Divide each element by n
Your Task
Write a function array_arithmetic(arr, n) that returns a dictionary with:
- "add": Array after adding n (as list)
- "subtract": Array after subtracting n (as list)
- "multiply": Array after multiplying by n (as list)
- "divide": Array after dividing by n (as list, rounded to 2 decimals)
Output Format
Return a dictionary with exactly these four keys.
Example:
arr = [10, 20, 30], n = 5
{'add': [15, 25, 35], 'subtract': [5, 15, 25], 'multiply': [50, 100, 150], 'divide': [2.0, 4.0, 6.0]}Element-wise operations apply to each element
Constraints:
- n will never be 0
- Round division results to 2 decimal places
Background Knowledge
NumPy Array Fundamentals
NumPy arrays are the standard representation for numerical data in Python. They enable efficient computation through vectorization—applying operations to entire arrays without explicit loops. Key features include:
- Element-wise operations: Arithmetic operators (+, -, *, /) automatically apply to each element when used with scalars or compatible arrays
- Broadcasting: NumPy automatically aligns arrays of different shapes for operations
- Type consistency: Arrays maintain uniform data types, which enables optimized C-level computation
Vectorization Benefits
Rather than iterating through elements individually, vectorized operations delegate computation to optimized compiled C code, resulting in significant performance improvements. This is why NumPy is fundamental to scientific computing across physics, chemistry, astronomy, and machine learning.
Algorithm Approach
This problem leverages NumPy's element-wise arithmetic operations. The approach is straightforward:
- Apply each arithmetic operation to the input array using NumPy's built-in operators
- Convert results to Python lists for dictionary storage
- Round division results to 2 decimal places using np.round()
No complex algorithms are needed—NumPy handles the heavy lifting internally through vectorized operations.
Step-by-Step Strategy
Step 1: Understand the Input
- arr: A NumPy array of numbers
- n: A scalar value (never 0)
Step 2: Perform Element-wise Operations
add_result = arr + n # Add n to each element
subtract_result = arr - n # Subtract n from each element
multiply_result = arr * n # Multiply each element by n
divide_result = arr / n # Divide each element by n
Step 3: Round Division Results
divide_result = np.round(divide_result, 2)
Step 4: Convert to Lists Use .tolist() to convert NumPy arrays to Python lists for dictionary storage.
Step 5: Return Dictionary
return {
"add": add_result.tolist(),
"subtract": subtract_result.tolist(),
"multiply": multiply_result.tolist(),
"divide": divide_result.tolist()
}
Complete Solution
import numpy as np
def array_arithmetic(arr, n):
"""
Perform basic arithmetic operations on a NumPy array.
Args:
arr: NumPy array of numbers
n: Scalar value (never 0)
Returns:
Dictionary with keys: 'add', 'subtract', 'multiply', 'divide'
"""
return {
"add": (arr + n).tolist(),
"subtract": (arr - n).tolist(),
"multiply": (arr * n).tolist(),
"divide": np.round(arr / n, 2).tolist()
}
# Test with sample
arr = np.array([10, 20, 30])
result = array_arithmetic(arr, 5)
print(result)
# Output: {'add': [15, 25, 35], 'subtract': [5, 15, 25], 'multiply': [50, 100, 150], 'divide': [2.0, 4.0, 6.0]}
Common Pitfalls
1. Forgetting to Convert to Lists NumPy arrays won't serialize properly in all contexts. Always use .tolist() when returning data as dictionaries.
2. Incorrect Rounding Placement Round before converting to a list:
# ✓ Correct
np.round(arr / n, 2).tolist()
# ✗ Incorrect (loses precision control)
round(arr / n, 2).tolist()
3. Data Type Issues Division in NumPy produces floating-point results. Ensure your output format matches expectations (floats, not integers).
4. Not Handling Edge Cases While the problem states n ≠0, always validate inputs in production code to prevent division by zero.
Time & Space Complexity
Time Complexity: O(m), where m is the number of elements in the array
Each arithmetic operation requires a single pass through all elements. NumPy's vectorized operations execute in linear time with respect to array size.
Space Complexity: O(m)
Each operation creates a new array of size m. The dictionary stores four arrays, but this is still O(m) overall since we're not creating nested or exponentially-sized structures.
Why Vectorization Matters
While the algorithmic complexity is the same as a Python loop, vectorized NumPy operations are typically 10-100x faster in practice due to:
- Compiled C implementation
- CPU cache optimization
- SIMD (Single Instruction Multiple Data) utilization