Bird
0
0

What is the best fix for this broadcasting error?

medium📝 Debug Q7 of 15
NumPy - Broadcasting
What is the best fix for this broadcasting error?
import numpy as np
x = np.array([[1, 2, 3], [4, 5, 6]])
y = np.array([1, 2])
z = x + y
AReshape y to (3,1) before addition
BReshape y to (1,2) before addition
CReshape y to (2,1) before addition
DNo fix needed, code runs fine
Step-by-Step Solution
Solution:
  1. Step 1: Check shapes of x and y

    x shape is (2,3), y shape is (2,). Shapes are incompatible for broadcasting.
  2. Step 2: Reshape y to match x's first dimension

    Reshaping y to (2,1) allows broadcasting across columns.
  3. Final Answer:

    Reshape y to (2,1) before addition -> Option C
  4. Quick Check:

    Reshape y to (2,1) fixes broadcasting error [OK]
Quick Trick: Match dimensions by reshaping arrays to fix broadcasting errors [OK]
Common Mistakes:
  • Reshaping to wrong shape causing new errors
  • Ignoring dimension order in reshaping
  • Assuming code runs without fix

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More NumPy Quizzes