Bird
0
0

You have a 3D array A with shape (2, 3, 4) and a 1D array B with shape (4,). You want to add B to each 2D slice of A along the last axis. Which code correctly uses broadcasting to do this?

hard📝 Application Q15 of 15
NumPy - Broadcasting
You have a 3D array A with shape (2, 3, 4) and a 1D array B with shape (4,). You want to add B to each 2D slice of A along the last axis. Which code correctly uses broadcasting to do this?
A<code>C = A + B</code>
B<code>C = A + B.reshape(4, 1)</code>
C<code>C = A + B.reshape(1, 3)</code>
D<code>C = A + B.reshape(2, 3, 4)</code>
Step-by-Step Solution
Solution:
  1. Step 1: Understand shapes and broadcasting rules

    A shape is (2,3,4), B shape is (4,). Broadcasting aligns from the right, so B broadcasts along last axis of A.
  2. Step 2: Evaluate each option's effect

    C = A + B adds B directly, broadcasting B over last axis. C = A + B.reshape(4, 1) reshapes B to (4,1), incompatible with A's shape. C = A + B.reshape(1, 3) reshapes B to (1,3), which does not match A's last two dims. C = A + B.reshape(2, 3, 4) reshapes B to (2,3,4), but B has only 4 elements, so reshape fails.
  3. Final Answer:

    C = A + B -> Option A
  4. Quick Check:

    1D array matches last axis of 3D array [OK]
Quick Trick: Add 1D array matching last axis directly to 3D array [OK]
Common Mistakes:
  • Trying to reshape 1D array incorrectly
  • Assuming reshape is needed when broadcasting works
  • Confusing axis order in reshaping

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More NumPy Quizzes