Bird
0
0

What will happen when running this code?

medium📝 Predict Output Q5 of 15
NumPy - Broadcasting
What will happen when running this code?
import numpy as np
x = np.array([1, 2, 3])
y = np.array([[1], [2]])
print(x + y)
ABroadcasting error due to incompatible shapes
B[[2 3 4] [3 4 5]]
C[[2 3] [3 4] [4 5]]
D[[1 2 3] [1 2 3]]
Step-by-Step Solution
Solution:
  1. Step 1: Check shapes of x and y

    x shape is (3,), y shape is (2,1). Shapes are compatible for broadcasting.
  2. Step 2: Apply broadcasting

    y broadcasts across columns, x broadcasts across rows, resulting in shape (2,3).
  3. Final Answer:

    [[2 3 4] [3 4 5]] -> Option B
  4. Quick Check:

    Broadcasting expands y and x to (2,3) shape [OK]
Quick Trick: Broadcasting aligns dimensions from the end for addition [OK]
Common Mistakes:
  • Assuming shape mismatch causes error
  • Confusing output shape
  • Ignoring broadcasting rules for 1D and 2D arrays

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More NumPy Quizzes