0
0
NumPydata~20 mins

Broadcasting compatibility check 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 shape check
What is the output of the following code that checks if two arrays can be broadcast together?
NumPy
import numpy as np
shape1 = (3, 1, 5)
shape2 = (1, 4, 5)
result = np.broadcast_shapes(shape1, shape2)
print(result)
A(3, 4, 5)
B(3, 1, 5, 4, 5)
CValueError: shape mismatch: objects cannot be broadcast to a single shape
D(3, 4)
Attempts:
2 left
💡 Hint
Broadcasting compares shapes from the right side, matching dimensions or using 1 to expand.
Predict Output
intermediate
2:00remaining
Broadcasting compatibility check result
What happens when you try to broadcast these shapes using numpy.broadcast_shapes?
NumPy
import numpy as np
shape1 = (2, 3)
shape2 = (3, 2)
try:
    result = np.broadcast_shapes(shape1, shape2)
except Exception as e:
    result = type(e).__name__
print(result)
A(2, 3, 3, 2)
BValueError
C(3, 3)
DTypeError
Attempts:
2 left
💡 Hint
Broadcasting requires dimensions to be equal or one of them to be 1 from the right side.
data_output
advanced
2:00remaining
Resulting shape after broadcasting arrays
Given two arrays with shapes (4, 1, 6) and (3, 6), what is the shape of the result after broadcasting?
NumPy
import numpy as np
arr1 = np.zeros((4, 1, 6))
arr2 = np.zeros((3, 6))
result = np.broadcast(arr1, arr2)
print(result.shape)
A(4, 1, 6, 3, 6)
B(3, 6)
CValueError
D(4, 3, 6)
Attempts:
2 left
💡 Hint
Broadcasting aligns shapes from the right and expands dimensions of size 1.
🔧 Debug
advanced
2:00remaining
Identify the broadcasting error
Which option shows the code that will raise a broadcasting error when adding two numpy arrays?
A
import numpy as np
x = np.ones((2, 3))
y = np.ones((3, 2))
result = x + y
B
import numpy as np
x = np.ones((5, 1))
y = np.ones((1, 4))
result = x + y
C
import numpy as np
x = np.ones((3, 1, 2))
y = np.ones((1, 4, 2))
result = x + y
D
import numpy as np
x = np.ones((1, 3))
y = np.ones((3, 1))
result = x + y
Attempts:
2 left
💡 Hint
Check if dimensions align from the right or are 1 for broadcasting.
🚀 Application
expert
3:00remaining
Determine output shape for complex broadcasting
You have arrays with shapes (7, 1, 5, 1) and (1, 3, 1, 4). What is the shape of the result after broadcasting these arrays?
NumPy
import numpy as np
shape1 = (7, 1, 5, 1)
shape2 = (1, 3, 1, 4)
result_shape = np.broadcast_shapes(shape1, shape2)
print(result_shape)
A(7, 1, 5, 4)
B(1, 3, 5, 1)
C(7, 3, 5, 4)
DValueError
Attempts:
2 left
💡 Hint
Broadcasting expands dimensions where one shape has 1 and the other has a size >1.