Bird
0
0

What will be the output of this code?

medium📝 Predict Output Q4 of 15
NumPy - Broadcasting
What will be the output of this code?
import numpy as np
x = np.array([[2, 4, 6], [8, 10, 12]])
y = np.array([1, 0, -1])
print(x - y)
A[[3 4 5] [7 10 13]]
B[[1 4 7] [9 10 11]]
C[[1 4 7] [7 10 11]]
D[[1 4 7] [7 10 13]]
Step-by-Step Solution
Solution:
  1. Step 1: Understand shapes

    x shape is (2, 3), y shape is (3,). Broadcasting subtracts y from each row of x.
  2. Step 2: Perform element-wise subtraction

    Row 1: [2-1, 4-0, 6-(-1)] = [1, 4, 7]
    Row 2: [8-1, 10-0, 12-(-1)] = [7, 10, 13]
  3. Step 3: Match output

    [[1 4 7] [7 10 13]] matches the computed result exactly.
  4. Final Answer:

    [[1 4 7] [7 10 13]] -> Option D
  5. Quick Check:

    Subtract 1D array from each row element-wise. [OK]
Quick Trick: Subtract 1D array from each row of 2D array element-wise. [OK]
Common Mistakes:
  • Incorrect sign handling for negative elements.
  • Mixing up rows and columns during subtraction.
  • Misreading array shapes for broadcasting.

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More NumPy Quizzes