0
0
NumPydata~20 mins

Avoiding broadcasting mistakes 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
What is the output of this NumPy code?
Consider the following code snippet using NumPy arrays. What will be the shape of the result array c?
NumPy
import numpy as np

a = np.array([[1, 2, 3], [4, 5, 6]])
b = np.array([10, 20])
c = a + b
ARaises a ValueError
B(2, 2)
C(3, 2)
D(2, 3)
Attempts:
2 left
💡 Hint
Check the shapes of the arrays before addition and how broadcasting rules apply.
data_output
intermediate
2:00remaining
What is the resulting array after broadcasting?
Given the arrays below, what is the output of c after the addition?
NumPy
import numpy as np

a = np.array([[1], [2], [3]])
b = np.array([10, 20, 30])
c = a + b
ARaises a ValueError
B
[[11 12 13]
 [21 22 23]
 [31 32 33]]
C
[[10 20 30]
 [10 20 30]
 [10 20 30]]
D
[[11 21 31]
 [12 22 32]
 [13 23 33]]
Attempts:
2 left
💡 Hint
Remember how broadcasting works when one array has shape (3,1) and the other (3,).
🔧 Debug
advanced
2:00remaining
Why does this broadcasting cause an error?
Examine the code below. Why does the addition raise an error?
NumPy
import numpy as np

x = np.ones((4, 1, 3))
y = np.ones((3, 4))
z = x + y
AThe arrays have different numbers of dimensions causing a ValueError
BThe arrays have different data types causing a TypeError
CShapes (4,1,3) and (3,4) are incompatible because trailing dimensions don't match and none is 1
DThe arrays have the same shape so no error occurs
Attempts:
2 left
💡 Hint
Check how NumPy aligns shapes from the right when broadcasting.
visualization
advanced
2:00remaining
Visualize broadcasting shapes
Which option correctly shows the broadcasted shapes of arrays a and b before addition?
NumPy
import numpy as np

a = np.ones((2, 1, 4))
b = np.ones((1, 3, 1))
c = a + b
print(c.shape)
A(2, 3, 4)
B(2, 1, 4)
C(1, 3, 1)
DRaises a ValueError
Attempts:
2 left
💡 Hint
Broadcasting aligns shapes from the right and expands dimensions of size 1.
🧠 Conceptual
expert
2:00remaining
Which broadcasting rule explains this behavior?
Given arrays a with shape (5, 1, 7) and b with shape (1, 3, 1), which NumPy broadcasting rule allows their addition?
ABroadcasting requires both arrays to have the same total number of elements
BArrays must have the same number of dimensions to broadcast
CBroadcasting only works if one array is 1D and the other is 2D
DDimensions are compared from right to left; sizes must be equal or one must be 1 to broadcast
Attempts:
2 left
💡 Hint
Think about how NumPy compares dimensions when broadcasting.