📘
Scalar Broadcasting
Problem Statement
Apply scalar operations to arrays using broadcasting.
Background
Broadcasting allows NumPy to work with arrays of different shapes:
- Scalar + array: adds scalar to every element
- Scalar * array: multiplies every element
- This is much faster than Python loops!
Your Task
Write a function scalar_ops(arr, scalar) that performs operations.
Output Format
Return a dictionary with:
- "add": arr + scalar (as list)
- "multiply": arr * scalar (as list)
- "power": arr ** scalar (as list)
- "divide": arr / scalar (rounded to 2 decimals, as list)
Example:
Input:
arr = [1, 2, 3, 4], scalar = 2
Output:
{'add': [3, 4, 5, 6], 'multiply': [2, 4, 6, 8], 'power': [1, 4, 9, 16], 'divide': [0.5, 1.0, 1.5, 2.0]}Reasoning:
Broadcasting applies scalar to each element
Constraints:
- scalar will be non-zero
- Round division to 2 decimal places
Editor
Python 3.13.1
Test Results
0/0Run code to see test results.