Challenge - 5 Problems
Broadcasting Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of broadcasting with different shapes
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 broadcasting smaller arrays.
✗ Incorrect
The array arr2 with shape (3,) is broadcasted to match arr1's shape (2,3). Each row of arr1 adds the arr2 values element-wise.
❓ data_output
intermediate2:00remaining
Result shape after broadcasting
Given these arrays, what is the shape of the result after broadcasting and addition?
NumPy
import numpy as np arr1 = np.ones((4,1,3)) arr2 = np.ones((1,5,1)) result = arr1 + arr2 print(result.shape)
Attempts:
2 left
💡 Hint
Broadcasting aligns dimensions from the right and expands dimensions of size 1.
✗ Incorrect
arr1 shape (4,1,3) and arr2 shape (1,5,1) broadcast to (4,5,3) by expanding the singleton dimensions.
🔧 Debug
advanced2:00remaining
Identify the error in broadcasting
What error does this code raise and why?
NumPy
import numpy as np arr1 = np.array([1, 2, 3]) arr2 = np.array([[1, 2], [3, 4]]) result = arr1 + arr2 print(result)
Attempts:
2 left
💡 Hint
Check if the shapes of the arrays can be broadcasted according to NumPy rules.
✗ Incorrect
arr1 has shape (3,) and arr2 has shape (2,2). These shapes are incompatible for broadcasting, causing a ValueError.
🚀 Application
advanced2:00remaining
Using broadcasting to normalize data
You have a 2D NumPy array representing data samples (rows) and features (columns). How can you subtract the mean of each feature from the data using broadcasting?
NumPy
import numpy as np data = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) mean = np.mean(data, axis=0) normalized = ??? print(normalized)
Attempts:
2 left
💡 Hint
The mean shape is (number_of_features,), you need to align it with data shape (samples, features).
✗ Incorrect
mean has shape (3,), data has shape (3,3). Reshaping mean to (1,3) aligns it for broadcasting across rows.
🧠 Conceptual
expert2:00remaining
Why advanced broadcasting improves performance
Why does using advanced broadcasting in NumPy often lead to faster code compared to explicit loops?
Attempts:
2 left
💡 Hint
Think about how NumPy handles operations internally compared to Python loops.
✗ Incorrect
NumPy broadcasting leverages optimized compiled code and vectorized operations, avoiding slow Python loops and improving speed.