Bird
0
0

Identify the error in this code snippet:

medium📝 Debug Q6 of 15
NumPy - Broadcasting
Identify the error in this code snippet:
import numpy as np
A = np.array([1, 2, 3])
B = np.array([[1, 2], [3, 4]])
C = A + B
AShapes (3,) and (2,2) are incompatible for broadcasting
BData types of A and B do not match
CArrays must be transposed before addition
DNo error, code runs correctly
Step-by-Step Solution
Solution:
  1. Step 1: Check shapes of A and B

    A shape is (3,), B shape is (2,2). These shapes cannot broadcast because dimensions differ and none is 1.
  2. Step 2: Confirm broadcasting rules

    Broadcasting requires dimensions to be equal or one to be 1, which is not true here.
  3. Final Answer:

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

    Broadcasting fails if shapes incompatible [OK]
Quick Trick: Check shape compatibility before adding arrays [OK]
Common Mistakes:
  • Assuming broadcasting always works
  • Ignoring shape mismatch
  • Thinking transpose fixes shape issues

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More NumPy Quizzes