v9.1.1
Menu

Basic Array Arithmetic

easyFREEArray MathematicsNumPy MathematicsNumpy

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

Input
arr = [10, 20, 30], n = 5
Output
{'add': [15, 25, 35], 'subtract': [5, 15, 25], 'multiply': [50, 100, 150], 'divide': [2.0, 4.0, 6.0]}
Reasoning
  • Inputs: arr is a 1-D array of three integers, (10,20,30)(10, 20, 30) (writing xix_i for the ii-th entry), and n =5= 5 is a single number. The same nn is combined with every entry independently, so each output list has 3 entries, one per input position.
  • Add: xi+5x_i + 5 gives 10+5=1510+5=15, 20+5=2520+5=25, 30+5=3530+5=35, so 'add' is [15, 25, 35].
  • Subtract: xi−5x_i - 5 gives 5,15,255, 15, 25.
  • Multiply: xi×5x_i \times 5 gives 50,100,15050, 100, 150.
  • Divide: xi/5x_i / 5 gives 10/5=210/5 = 2, 20/5=420/5 = 4, 30/5=630/5 = 6, and rounding to 2 decimal places leaves them unchanged: [2.0, 4.0, 6.0].
  • Output: a dictionary with the four keys 'add', 'subtract', 'multiply', 'divide', each holding a plain list. Notice that only the quotients print as 2.0 rather than 2: adding, subtracting or multiplying integers keeps them whole, but division is real-valued even when it comes out exact. A quotient that doesn't terminate, such as 10/3=3.333…10/3 = 3.333\ldots, is why the rounding rule exists: it would become 3.333.33.

Constraints

  • n will never be 0
  • Round division results to 2 decimal places

More from Numpy

solution.py

Test results

Sign in to run your code against the test cases.