Bird
0
0

Consider the code:

medium📝 Debug Q14 of 15
NumPy - Broadcasting
Consider the code:
import numpy as np
x = np.ones((2,3))
y = np.ones((3,2))
z = x + y

What error will occur and why?
AValueError because shapes (2,3) and (3,2) are incompatible for broadcasting
BTypeError because arrays have different data types
CNo error, result shape is (2,3)
DSyntaxError due to invalid addition
Step-by-Step Solution
Solution:
  1. Step 1: Check shapes of x and y

    x shape is (2,3), y shape is (3,2). Compare dims right to left: 3 vs 2 and 2 vs 3.
  2. Step 2: Apply broadcasting rules

    Neither dimension matches or is 1, so broadcasting fails and raises ValueError.
  3. Final Answer:

    ValueError because shapes (2,3) and (3,2) are incompatible for broadcasting -> Option A
  4. Quick Check:

    Broadcasting fails if dims differ and neither is 1 [OK]
Quick Trick: Broadcast dims must be equal or 1; else error [OK]
Common Mistakes:
  • Assuming addition works despite shape mismatch
  • Confusing error type as TypeError or SyntaxError
  • Ignoring dimension order in shapes

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More NumPy Quizzes