Bird
0
0

Which numpy code snippet correctly adds a 1D array to each row of a 2D array using broadcasting?

easy📝 Syntax Q3 of 15
NumPy - Broadcasting
Which numpy code snippet correctly adds a 1D array to each row of a 2D array using broadcasting?
Anp.array([[1,2],[3,4]]) + np.array([1,2])
Bnp.array([[1,2],[3,4]]) + np.array([[1,2]])
Cnp.array([[1,2],[3,4]]) + np.array([[1],[2]])
Dnp.array([[1,2],[3,4]]) + np.array([1,2,3])
Step-by-Step Solution
Solution:
  1. Step 1: Understand shapes involved

    The 2D array has shape (2,2). The 1D array with shape (2,) can broadcast across rows.
  2. Step 2: Check each option's shape compatibility

    np.array([[1,2],[3,4]]) + np.array([1,2]) adds (2,2) + (2,) which broadcasts correctly. np.array([[1,2],[3,4]]) + np.array([[1,2]]) is (2,2) + (1,2) also works but is less common. np.array([[1,2],[3,4]]) + np.array([[1],[2]]) shape (2,1) adds column-wise. np.array([[1,2],[3,4]]) + np.array([1,2,3]) shape (3,) incompatible.
  3. Final Answer:

    np.array([[1,2],[3,4]]) + np.array([1,2]) -> Option A
  4. Quick Check:

    Adding 1D array to 2D rows = np.array([[1,2],[3,4]]) + np.array([1,2]) [OK]
Quick Trick: 1D array shape matches columns to add to rows [OK]
Common Mistakes:
  • Using incompatible shapes causing errors
  • Confusing row-wise and column-wise addition
  • Adding arrays with different lengths

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More NumPy Quizzes