Bird
0
0

What is the issue with this code snippet?

medium📝 Debug Q6 of 15
NumPy - Broadcasting
What is the issue with this code snippet?
import numpy as np
a = np.array([[1, 2], [3, 4]])
b = np.array([1, 2, 3])
print(a + b)
A'b' needs to be reshaped to (3, 1) before addition.
BShapes of 'a' and 'b' are incompatible for broadcasting.
CThe code will run without any errors.
D'a' should be a 1D array to add with 'b'.
Step-by-Step Solution
Solution:
  1. Step 1: Check shapes

    a shape is (2, 2), b shape is (3,). These shapes are incompatible for broadcasting.
  2. Step 2: Broadcasting rules

    For broadcasting, trailing dimensions must be equal or one of them must be 1. Here, 2 vs 3 fails this rule.
  3. Step 3: Result

    Attempting a + b raises a ValueError due to incompatible shapes.
  4. Final Answer:

    Shapes of 'a' and 'b' are incompatible for broadcasting. -> Option B
  5. Quick Check:

    Check trailing dimensions for broadcasting compatibility. [OK]
Quick Trick: Trailing dimensions must match or be 1 for broadcasting. [OK]
Common Mistakes:
  • Assuming any shapes can broadcast without checking dimensions.
  • Trying to reshape arrays incorrectly without understanding rules.
  • Ignoring error messages about shape incompatibility.

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More NumPy Quizzes