Bird
0
0

Examine the following code:

medium📝 Debug Q6 of 15
NumPy - Broadcasting
Examine the following code:
import numpy as np
arr1 = np.ones((4,2))
arr2 = np.ones((2,4))
result = arr1 + arr2

What issue will arise when executing this code?
ATypeError because arrays have different data types
BNo error; arrays will broadcast and add correctly
CValueError due to incompatible shapes for broadcasting
DSyntaxError due to incorrect numpy import
Step-by-Step Solution
Solution:
  1. Step 1: Check shapes

    arr1 has shape (4,2), arr2 has shape (2,4).
  2. Step 2: Apply broadcasting rules

    Broadcasting compares dimensions from the end: 2 vs 4 (not equal and neither is 1), so broadcasting fails.
  3. Final Answer:

    ValueError due to incompatible shapes for broadcasting -> Option C
  4. Quick Check:

    Dimension mismatch without 1 in either dimension causes error [OK]
Quick Trick: Broadcasting requires matching or 1 in dimensions [OK]
Common Mistakes:
  • Assuming arrays with same numbers but different order broadcast
  • Ignoring dimension order when broadcasting
  • Confusing ValueError with TypeError

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More NumPy Quizzes