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 adding arrays with broadcasting
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
Think about how NumPy aligns shapes when adding arrays of different dimensions.
✗ Incorrect
NumPy broadcasts the 1D array arr1 across each row of the 2D arr2, adding element-wise to produce a 3x3 array.
❓ data_output
intermediate1:30remaining
Shape of result after broadcasting
Given these arrays, what is the shape of the result after broadcasting and addition?
NumPy
import numpy as np x = np.ones((4,1)) y = np.arange(3) z = x + y
Attempts:
2 left
💡 Hint
Broadcasting expands dimensions to match the largest shape.
✗ Incorrect
x has shape (4,1) and y has shape (3,). y is treated as (1,3). Broadcasting results in (4,3).
🔧 Debug
advanced2:00remaining
Identify the broadcasting error
Why does this code raise an error?
NumPy
import numpy as np arr1 = np.array([1, 2]) arr2 = np.array([[1, 2, 3], [4, 5, 6]]) result = arr1 + arr2
Attempts:
2 left
💡 Hint
Check if the shapes of the arrays can be broadcast together.
✗ Incorrect
arr1 shape is (2,) and arr2 shape is (2,3). These shapes are incompatible for broadcasting.
🚀 Application
advanced2:30remaining
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
Consider the shape of the mean array and how broadcasting works for subtraction.
✗ Incorrect
Using keepdims=True keeps the mean shape compatible for broadcasting across rows.
🧠 Conceptual
expert3:00remaining
Why broadcasting improves performance
Why does NumPy use broadcasting instead of explicit loops for operations on arrays of different shapes?
Attempts:
2 left
💡 Hint
Think about memory usage and speed when working with large data.
✗ Incorrect
Broadcasting lets NumPy perform operations without copying data unnecessarily, improving speed and memory use.