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
arr = np.array([1, 2, 3])
scalar = np.array([5])
result = arr + scalar
print(result)
AOutput is [1 2 3 5]
BError because scalar is an array, not a number
CNo error; output is [6 7 8]
DError due to shape mismatch
Step-by-Step Solution
Solution:
  1. Step 1: Check shapes of arrays

    arr shape is (3,), scalar shape is (1,). Broadcasting allows (1,) to expand to (3,).
  2. Step 2: Apply broadcasting addition

    Each element of arr is added to 5, resulting in [6, 7, 8].
  3. Final Answer:

    No error; output is [6 7 8] -> Option C
  4. Quick Check:

    Broadcasting works with (3,) + (1,) arrays [OK]
Quick Trick: Arrays with shape (n,) and (1,) broadcast correctly [OK]
Common Mistakes:
  • Assuming scalar must be a plain number
  • Thinking shape mismatch causes error
  • Expecting concatenation instead of addition

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More NumPy Quizzes