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, 5, 6]])
Y = np.array([1, 2])
Z = X + Y
AX and Y have incompatible data types
BY should be transposed before addition
CY should be reshaped to (2,1) to broadcast with X
DNo mistake, broadcasting works fine
Step-by-Step Solution
Solution:
  1. Step 1: Check shapes of X and Y

    X shape is (2,3), Y shape is (2,). These shapes are incompatible for broadcasting.
  2. Step 2: Fix shape of Y

    Reshape Y to (2,1) so it broadcasts across columns of X.
  3. Final Answer:

    Y should be reshaped to (2,1) to broadcast with X -> Option C
  4. Quick Check:

    Broadcast needs compatible shapes, reshape if needed [OK]
Quick Trick: Reshape 1D arrays to match 2D for broadcasting [OK]
Common Mistakes:
  • Assuming 1D arrays broadcast on rows automatically
  • Trying to transpose instead of reshape
  • Ignoring shape mismatch errors

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More NumPy Quizzes