v9.1.1
Menu

Scalar Broadcasting

easyFREEBroadcastingNumPy BroadcastingNumPy Foundations

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
  • Inputs: arr is a 1-D array of four integers [1,2,3,4][1, 2, 3, 4] and scalar is the single number 22. The scalar is paired with every element in turn, as if it were stretched into [2,2,2,2][2, 2, 2, 2].
  • Add: xi+2x_i + 2 gives 1+2,2+2,3+2,4+2=[3,4,5,6]1+2, 2+2, 3+2, 4+2 = [3, 4, 5, 6].
  • Multiply: 2xi2x_i gives [2,4,6,8][2, 4, 6, 8].
  • Power: each element raised to the scalar, xi2x_i^2, gives 1,4,9,161, 4, 9, 16. The scalar is the exponent, not the base, so this is not 2xi2^{x_i}.
  • Divide: xi/2x_i / 2 gives 0.5,1.0,1.5,2.00.5, 1.0, 1.5, 2.0, which are already exact at 2 decimal places. With scalar = 3 you would see 2/3≈0.672/3 \approx 0.67.
  • Output: a dictionary with keys add, multiply, power, divide, each mapped to a plain list the same length as arr. Notice that the first three lists stay integers, while division always produces floats: 2.0, not 2.

Constraints

  • scalar will be non-zero
  • Round division to 2 decimal places

Learn this in

More from NumPy Foundations

solution.py

Test results

Sign in to run your code against the test cases.