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 with 3D and 2D arrays
What is the output of the following code snippet?
NumPy
import numpy as np A = np.ones((2,3,4)) B = np.arange(4) result = A + B print(result)
Attempts:
2 left
💡 Hint
Remember how numpy broadcasts arrays with different shapes by matching dimensions from the right.
✗ Incorrect
Array A has shape (2,3,4) filled with ones. Array B has shape (4,). When adding, B is broadcasted to (1,1,4) and then to (2,3,4). So each element in the last dimension of A is added to the corresponding element in B. The result is a (2,3,4) array where each 4-element vector is [1+0, 1+1, 1+2, 1+3] = [1,2,3,4].
❓ data_output
intermediate1:30remaining
Shape after broadcasting multiplication
Given the arrays below, what is the shape of the result after multiplication?
NumPy
import numpy as np X = np.ones((4,1,3)) Y = np.arange(3) result = X * Y print(result.shape)
Attempts:
2 left
💡 Hint
Check how numpy aligns dimensions from the right and broadcasts accordingly.
✗ Incorrect
X has shape (4,1,3), Y has shape (3,). Y is broadcasted to (1,1,3) to match X. Multiplication results in shape (4,1,3).
🔧 Debug
advanced1:30remaining
Identify the error in broadcasting with incompatible shapes
What error will the following code raise?
NumPy
import numpy as np A = np.ones((2,3,4)) B = np.arange(5) result = A + B
Attempts:
2 left
💡 Hint
Check if the shapes can be broadcasted according to numpy rules.
✗ Incorrect
Array A has shape (2,3,4), B has shape (5,). The last dimensions 4 and 5 do not match and neither is 1, so broadcasting fails with a ValueError.
🚀 Application
advanced2:30remaining
Using broadcasting to normalize a 3D array
You have a 3D array representing 2 samples, each with 3 features and 4 observations. You want to subtract the mean of each feature across observations from the array. Which code correctly does this using broadcasting?
NumPy
import numpy as np arr = np.array([[[1,2,3,4],[5,6,7,8],[9,10,11,12]], [[13,14,15,16],[17,18,19,20],[21,22,23,24]]]) # Compute mean and subtract
Attempts:
2 left
💡 Hint
Think about which axis corresponds to observations and how to keep dimensions for broadcasting.
✗ Incorrect
Observations are along axis 2. Taking mean along axis 2 with keepdims=True keeps shape compatible for broadcasting subtraction.
🧠 Conceptual
expert2:00remaining
Understanding broadcasting rules with higher dimensions
Given arrays A with shape (3,1,5,1) and B with shape (1,4,1,6), what is the shape of the result when computing A + B?
Attempts:
2 left
💡 Hint
Align shapes from the right and apply broadcasting rules dimension-wise.
✗ Incorrect
Aligning shapes:
A: (3,1,5,1)
B: (1,4,1,6)
Dimension-wise:
3 vs 1 -> 3
1 vs 4 -> 4
5 vs 1 -> 5
1 vs 6 -> 6
Result shape is (3,4,5,6).