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 snippet 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 the smaller array.
✗ Incorrect
The array arr2 with shape (3,) is broadcast across the rows of arr1 with shape (2,3). Each element in arr2 is added to the corresponding column in arr1.
❓ data_output
intermediate1:30remaining
Shape after broadcasting
Given these arrays, what is the shape of the result after broadcasting and 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
Check how the shapes (4,1) and (3,) align for broadcasting.
✗ Incorrect
The array arr1 has shape (4,1) and arr2 has shape (3,). NumPy broadcasts arr2 to (1,3), then both arrays broadcast to (4,3).
🔧 Debug
advanced1:30remaining
Identify the broadcasting error
What error does this code raise when trying to add these arrays?
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 of the arrays can be broadcast together.
✗ Incorrect
The shapes (2,2) and (3,) are incompatible for broadcasting because the trailing dimensions do not match and neither is 1.
❓ visualization
advanced2:30remaining
Visualize broadcasting with reshaping
Which option correctly reshapes arr2 to broadcast with arr1 for element-wise multiplication?
NumPy
import numpy as np import matplotlib.pyplot as plt arr1 = np.arange(6).reshape(2,3) arr2 = np.array([1, 2]) # Reshape arr2 here arr2_reshaped = ??? result = arr1 * arr2_reshaped plt.imshow(result) plt.colorbar() plt.show()
Attempts:
2 left
💡 Hint
arr1 shape is (2,3). To multiply, arr2 must broadcast to (2,3).
✗ Incorrect
Reshaping arr2 to (2,1) allows it to broadcast across the 3 columns of arr1, resulting in shape (2,3).
🧠 Conceptual
expert2:00remaining
Broadcasting rules application
Given arrays with shapes (5,1,4) and (1,3,1), what is the shape of their broadcasted result?
Attempts:
2 left
💡 Hint
Compare dimensions from right to left, applying broadcasting rules.
✗ Incorrect
Broadcasting compares dimensions from right to left: 4 and 1 broadcast to 4; 1 and 3 broadcast to 3; 5 and 1 broadcast to 5. Result shape is (5,3,4).