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 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)
Attempts:
2 left
💡 Hint
Adding a scalar to an array adds the scalar to each element.
✗ Incorrect
NumPy broadcasts the scalar 5 to each element of the array, so each element is increased by 5.
❓ data_output
intermediate2: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)
Attempts:
2 left
💡 Hint
Broadcasting matches dimensions from the right.
✗ Incorrect
arr2 is broadcast across the rows of arr1, so the result keeps arr1's shape (2,3).
🔧 Debug
advanced2: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
Attempts:
2 left
💡 Hint
Broadcasting requires compatible shapes from the right.
✗ Incorrect
Shapes (3,) and (2,2) are incompatible for broadcasting, causing a ValueError.
🚀 Application
advanced2: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
Attempts:
2 left
💡 Hint
Keep the mean shape compatible for broadcasting.
✗ Incorrect
Using keepdims=True keeps the mean shape (1, n) so it broadcasts correctly across rows.
🧠 Conceptual
expert2:00remaining
Broadcasting rules and shape compatibility
Which of these pairs of shapes can be broadcast together in NumPy without error?
Attempts:
2 left
💡 Hint
Broadcasting compares shapes from the right and dimensions must be equal or 1.
✗ Incorrect
Option D shapes (3,1,5) and (1,5) broadcast to (3,1,5) because trailing dims match or are 1.