0
0
NumPydata~20 mins

Common broadcasting patterns 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 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)
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 the smaller array.
data_output
intermediate
1:30remaining
Shape after broadcasting
Given these arrays, what is the shape of the result after broadcasting and 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(3, 4)
D(1, 3)
Attempts:
2 left
💡 Hint
Check how the shapes (4,1) and (3,) align for broadcasting.
🔧 Debug
advanced
1:30remaining
Identify the broadcasting error
What error does this code raise when trying to add these arrays?
NumPy
import numpy as np

arr1 = np.array([[1, 2], [3, 4]])
arr2 = np.array([1, 2, 3])
result = arr1 + arr2
ATypeError: unsupported operand type(s) for +: 'int' and 'list'
BValueError: operands could not be broadcast together with shapes (2,2) (3,)
CIndexError: index out of bounds
DNo error, output is [[2 4] [4 6]]
Attempts:
2 left
💡 Hint
Check if the shapes of the arrays can be broadcast together.
visualization
advanced
2:30remaining
Visualize broadcasting with reshaping
Which option correctly reshapes arr2 to broadcast with arr1 for element-wise multiplication?
NumPy
import numpy as np
import matplotlib.pyplot as plt

arr1 = np.arange(6).reshape(2,3)
arr2 = np.array([1, 2])

# Reshape arr2 here
arr2_reshaped = ???
result = arr1 * arr2_reshaped
plt.imshow(result)
plt.colorbar()
plt.show()
Aarr2.reshape(3,1)
Barr2.reshape(1,2)
Carr2.reshape(2,1)
Darr2.reshape(3,2)
Attempts:
2 left
💡 Hint
arr1 shape is (2,3). To multiply, arr2 must broadcast to (2,3).
🧠 Conceptual
expert
2:00remaining
Broadcasting rules application
Given arrays with shapes (5,1,4) and (1,3,1), what is the shape of their broadcasted result?
A(5, 3, 1)
B(5, 1, 1)
C(1, 3, 4)
D(5, 3, 4)
Attempts:
2 left
💡 Hint
Compare dimensions from right to left, applying broadcasting rules.