NumPy Operations & Broadcasting
Beginner
Scale and Shift an Array
Beginner
~8 min
code completion
Vectorized Scale and Shift
One of NumPy's core strengths is vectorized arithmetic — applying an operation to every element at once, without a Python loop.
Instead of:
result = [x * scale + shift for x in arr] # slow
Write:
result = arr * scale + shift # fast, vectorized
This works because NumPy overloads the arithmetic operators to operate element-wise.
Your task:
Implement scale_and_shift(arr, scale, shift) that multiplies every element by scale then adds shift.
Example Tests
Scale by 2, shift by 1
Input: {"arr":[1,2,3],"scale":2,"shift":1}
Expected: [3,5,7]
Scale 0.5, negative shift
Input: {"arr":[0,5,10],"scale":0.5,"shift":-1}
Expected: [-1,1.5,4]
Negative values, scale 3
Input: {"arr":[-2,-1,0,1,2],"scale":3,"shift":0}
Expected: [-6,-3,0,3,6]