Bird
0
0

Identify the error in this code snippet:

medium📝 Debug Q14 of 15
NumPy - Broadcasting
Identify the error in this code snippet:
import numpy as np
X = np.array([[1, 2], [3, 4], [5, 6]])
y = np.array([10, 20, 30])
result = X + y
Ay should be reshaped to (3,1) before addition
BNo error, code runs fine
CX and y must have the same number of columns
DShapes (3,2) and (3,) cannot broadcast together
Step-by-Step Solution
Solution:
  1. Step 1: Check shapes of X and y

    X shape is (3,2), y shape is (3,). Broadcasting rules require trailing dimensions to match or be 1.
  2. Step 2: Analyze broadcasting compatibility

    Here, last dims are 2 (X) and 1 (y) after broadcasting rules, so y broadcasts along columns. The addition works without error.
  3. Final Answer:

    No error, code runs fine -> Option B
  4. Quick Check:

    Broadcasting allows (3,2) + (3,) by treating (3,) as (3,1) [OK]
Quick Trick: Trailing dimensions must match or be 1 for broadcasting [OK]
Common Mistakes:
  • Assuming broadcasting works if first dims match
  • Not checking trailing dimension compatibility
  • Thinking reshaping y to (3,1) fixes addition here

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More NumPy Quizzes