Bird
0
0

What is the cause of the broadcasting error in this code?

medium📝 Debug Q6 of 15
NumPy - Broadcasting
What is the cause of the broadcasting error in this code?
import numpy as np
x = np.array([1, 2, 3])
y = np.array([[1, 2], [3, 4]])
z = x + y
Ax is 1D and y is 2D, which is not allowed
BData types of x and y are different
CShapes (3,) and (2,2) are incompatible for broadcasting
DThe arrays contain different numbers of elements
Step-by-Step Solution
Solution:
  1. Step 1: Check shapes

    x has shape (3,), y has shape (2,2).
  2. Step 2: Apply broadcasting rules

    Align shapes from right: (3) vs (2,2) - dimensions do not match and neither is 1.
  3. Final Answer:

    Shapes (3,) and (2,2) are incompatible for broadcasting -> Option C
  4. Quick Check:

    Check trailing dimensions for compatibility [OK]
Quick Trick: Broadcasting requires matching trailing dims or 1 [OK]
Common Mistakes:
  • Assuming 1D and 2D arrays always broadcast
  • Ignoring shape dimensions order
  • Confusing data type mismatch with shape mismatch

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More NumPy Quizzes