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 1D and 2D broadcasting addition
What is the output of this code snippet using NumPy broadcasting?
NumPy
import numpy as np arr1 = np.array([1, 2, 3]) arr2 = np.array([[10], [20], [30]]) result = arr1 + arr2 print(result)
Attempts:
2 left
💡 Hint
Remember how NumPy aligns shapes for broadcasting: the smaller array is stretched along missing dimensions.
✗ Incorrect
The 1D array [1,2,3] is broadcast across each row of the 2D array [[10],[20],[30]]. So each element in arr2 adds to each element in arr1, producing a 3x3 array where each row is arr1 plus the corresponding element of arr2.
❓ data_output
intermediate1:30remaining
Shape of result 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 arrays to match each other's shape along missing dimensions.
✗ Incorrect
arr1 has shape (4,1) and arr2 has shape (3,). NumPy treats arr2 as (1,3) to broadcast. The result shape is (4,3).
🔧 Debug
advanced1:30remaining
Identify the error in broadcasting shapes
What error will 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
Attempts:
2 left
💡 Hint
Check if the shapes can be aligned for broadcasting.
✗ Incorrect
The shapes (3,) and (2,2) cannot be broadcast because their dimensions do not match or are not 1.
❓ visualization
advanced2:00remaining
Visualize broadcasting result of subtraction
What does the printed array look like after this subtraction with broadcasting?
NumPy
import numpy as np arr1 = np.array([[5, 10, 15], [20, 25, 30]]) arr2 = np.array([1, 2, 3]) result = arr1 - arr2 print(result)
Attempts:
2 left
💡 Hint
Broadcast arr2 across rows of arr1 and subtract element-wise.
✗ Incorrect
arr2 is broadcast across each row of arr1. Subtracting element-wise gives the shown 2x3 array.
🧠 Conceptual
expert2:30remaining
Why does broadcasting fail for these shapes?
Given arrays with shapes (3,1) and (2,3), why does broadcasting fail when trying to add them?
Attempts:
2 left
💡 Hint
Broadcasting compares shapes from the right side dimension-wise.
✗ Incorrect
Broadcasting rules require each dimension to be equal or one of them to be 1. Here, the last dimensions 1 and 3 are compatible, but the next dimensions 3 and 2 are not.