Challenge - 5 Problems
Broadcasting Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of broadcasting addition
What is the output of this code using NumPy broadcasting?
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)
Attempts:
2 left
💡 Hint
Remember how NumPy adds arrays with compatible shapes by stretching smaller arrays.
✗ Incorrect
The array arr2 with shape (3,) is broadcast across the rows of arr1 with shape (2,3). So each row of arr1 adds the arr2 values element-wise.
❓ data_output
intermediate1:30remaining
Shape after broadcasting multiplication
Given these arrays, what is the shape of the result after multiplication?
NumPy
import numpy as np arr1 = np.ones((4, 1)) arr2 = np.array([1, 2, 3]) result = arr1 * arr2 print(result.shape)
Attempts:
2 left
💡 Hint
Broadcasting stretches dimensions of size 1 to match the other array.
✗ Incorrect
arr1 has shape (4,1) and arr2 has shape (3,). NumPy treats arr2 as (1,3) and broadcasts arr1 to (4,3). The result shape is (4,3).
🔧 Debug
advanced2:30remaining
Identify the broadcasting error
Which option shows code that will raise a broadcasting error?
NumPy
import numpy as np arr1 = np.array([[1, 2], [3, 4]]) arr2 = np.array([1, 2, 3]) result = arr1 + arr2
Attempts:
2 left
💡 Hint
Check if the shapes can be broadcast together.
✗ Incorrect
arr1 shape is (2,2), arr2 shape is (3,). These shapes are incompatible for broadcasting, so option C raises a ValueError.
🧠 Conceptual
advanced1:30remaining
Broadcasting rule for trailing dimensions
Which statement best describes NumPy's broadcasting rule for arrays with different shapes?
Attempts:
2 left
💡 Hint
Think about how NumPy compares shapes from the right side.
✗ Incorrect
NumPy compares shapes from the last dimension backward. Dimensions must be equal or one must be 1 to broadcast.
🚀 Application
expert3:00remaining
Using broadcasting to normalize data
You have a 2D NumPy array 'data' of shape (100, 5) representing 100 samples with 5 features each. You want to subtract the mean of each feature from the data using broadcasting. Which code correctly does this?
Attempts:
2 left
💡 Hint
Mean per feature means mean along samples axis.
✗ Incorrect
data.mean(axis=0) computes mean for each feature (column). Subtracting this 1D array broadcasts across rows, centering each feature.