0
0
NumPydata~20 mins

Broadcasting rules in NumPy - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Broadcasting Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of broadcasting addition
What is the output of this code 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)
A
[[11 22 33]
 [14 25 36]]
B
[[11 12 13]
 [14 15 16]]
C
[[10 20 30]
 [10 20 30]]
D
[[1 2 3 10 20 30]
 [4 5 6 10 20 30]]
Attempts:
2 left
💡 Hint
Remember how NumPy adds arrays with compatible shapes by stretching smaller arrays.
data_output
intermediate
1:30remaining
Shape after broadcasting multiplication
Given these arrays, what is the shape of the result after multiplication?
NumPy
import numpy as np

arr1 = np.ones((4, 1))
arr2 = np.array([1, 2, 3])
result = arr1 * arr2
print(result.shape)
A(4, 3)
B(4, 1)
C(1, 3)
D(3, 4)
Attempts:
2 left
💡 Hint
Broadcasting stretches dimensions of size 1 to match the other array.
🔧 Debug
advanced
2:30remaining
Identify the broadcasting error
Which option shows code that will raise a broadcasting error?
NumPy
import numpy as np

arr1 = np.array([[1, 2], [3, 4]])
arr2 = np.array([1, 2, 3])
result = arr1 + arr2
Aarr1 + arr2.reshape(3, 1)
Barr1 + arr2[:2]
Carr1 + arr2
Darr1 + arr2[:2].reshape(2, 1)
Attempts:
2 left
💡 Hint
Check if the shapes can be broadcast together.
🧠 Conceptual
advanced
1:30remaining
Broadcasting rule for trailing dimensions
Which statement best describes NumPy's broadcasting rule for arrays with different shapes?
AArrays are compatible if each dimension is equal or one of them is 1, starting from the trailing dimensions.
BArrays are compatible if the total number of elements is the same.
CArrays are compatible if their shapes are exactly the same.
DArrays are compatible only if the smaller array has fewer dimensions than the larger one.
Attempts:
2 left
💡 Hint
Think about how NumPy compares shapes from the right side.
🚀 Application
expert
3:00remaining
Using broadcasting to normalize data
You have a 2D NumPy array 'data' of shape (100, 5) representing 100 samples with 5 features each. You want to subtract the mean of each feature from the data using broadcasting. Which code correctly does this?
Adata - data.mean()
Bdata - data.mean(axis=1)
Cdata - data.mean(axis=0).reshape(100, 5)
Ddata - data.mean(axis=0)
Attempts:
2 left
💡 Hint
Mean per feature means mean along samples axis.