Bird
0
0

Find the mistake in this code that causes a broadcasting error:

medium📝 Debug Q7 of 15
NumPy - Broadcasting
Find the mistake in this code that causes a broadcasting error:
import numpy as np
X = np.array([[1, 2], [3, 4]])
Y = np.array([1, 2, 3])
Z = X + Y
print(Z)
AX and Y have different data types
BNo mistake, code runs fine
CX is not a numpy array
DY has incompatible shape (3,) for broadcasting with X shape (2,2)
Step-by-Step Solution
Solution:
  1. Step 1: Check shapes of X and Y

    X shape is (2,2), Y shape is (3,). Broadcasting compares dimensions from right to left.
  2. Step 2: Determine broadcasting compatibility

    Last dims: 2 vs 3 - not equal and neither is 1, so broadcasting fails.
  3. Final Answer:

    Y has incompatible shape (3,) for broadcasting with X shape (2,2) -> Option D
  4. Quick Check:

    Broadcasting requires compatible dimension sizes [OK]
Quick Trick: Broadcasting fails if last dims differ and neither is 1 [OK]
Common Mistakes:
  • Assuming data type mismatch causes error
  • Ignoring shape mismatch
  • Thinking code runs without error

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More NumPy Quizzes