0
0
NumPydata~20 mins

Scalar and array broadcasting in NumPy - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Broadcasting Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of scalar and array addition
What is the output of this code snippet using NumPy broadcasting?
NumPy
import numpy as np
arr = np.array([1, 2, 3])
result = arr + 5
print(result)
A[1 2 3 5]
B[6 7 8]
C[5 7 9]
DTypeError
Attempts:
2 left
💡 Hint
Adding a scalar to an array adds the scalar to each element.
data_output
intermediate
2:00remaining
Shape after broadcasting with different dimensions
Given the arrays below, what is the shape of the result after broadcasting and addition?
NumPy
import numpy as np
arr1 = np.array([[1, 2, 3], [4, 5, 6]])
arr2 = np.array([10, 20, 30])
result = arr1 + arr2
print(result.shape)
A(2, 3)
B(3, 2)
C(2,)
D(3,)
Attempts:
2 left
💡 Hint
Broadcasting matches dimensions from the right.
🔧 Debug
advanced
2:00remaining
Identify the error in broadcasting
What error does this code raise when trying to add these arrays?
NumPy
import numpy as np
arr1 = np.array([1, 2, 3])
arr2 = np.array([[1, 2], [3, 4]])
result = arr1 + arr2
ATypeError: unsupported operand type(s) for +: 'int' and 'list'
BNo error, outputs a (2,3) array
CValueError: operands could not be broadcast together with shapes (3,) (2,2)
DIndexError: index out of bounds
Attempts:
2 left
💡 Hint
Broadcasting requires compatible shapes from the right.
🚀 Application
advanced
2:00remaining
Using broadcasting to normalize data
You have a 2D array of data where each column needs to be normalized by subtracting the column mean. Which code correctly uses broadcasting to do this?
NumPy
import numpy as np
data = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
# Normalize columns by subtracting mean
Adata - data.mean(axis=0, keepdims=True)
Bdata - data.mean(axis=0)
Cdata - data.mean(axis=1)
Ddata - data.mean()
Attempts:
2 left
💡 Hint
Keep the mean shape compatible for broadcasting.
🧠 Conceptual
expert
2:00remaining
Broadcasting rules and shape compatibility
Which of these pairs of shapes can be broadcast together in NumPy without error?
A(4, 1, 3) and (3, 1)
B(5, 4) and (1, 4, 5)
C(2, 3, 4) and (3, 1)
D(3, 1, 5) and (1, 5)
Attempts:
2 left
💡 Hint
Broadcasting compares shapes from the right and dimensions must be equal or 1.