Bird
0
0

You want to create a 4x4 NumPy array filled with the value 9, but only the diagonal elements should be 0. Which code correctly achieves this using np.full() and other NumPy functions?

hard📝 Application Q15 of 15
NumPy - Creating Arrays
You want to create a 4x4 NumPy array filled with the value 9, but only the diagonal elements should be 0. Which code correctly achieves this using np.full() and other NumPy functions?
Aarr = np.zeros((4,4)); arr[:] = 9; print(arr)
Barr = np.full((4,4), 9); np.fill_diagonal(arr, 0); print(arr)
Carr = np.full((4,4), 0); np.fill_diagonal(arr, 9); print(arr)
Darr = np.full(4, 9); np.fill_diagonal(arr, 0); print(arr)
Step-by-Step Solution
Solution:
  1. Step 1: Create a 4x4 array filled with 9

    Using np.full((4,4), 9) creates a 4x4 array where every element is 9.
  2. Step 2: Replace diagonal elements with 0

    np.fill_diagonal(arr, 0) sets the diagonal elements of the array to 0.
  3. Step 3: Verify the output

    Printing arr shows a 4x4 array with 9 everywhere except 0 on the diagonal.
  4. Final Answer:

    arr = np.full((4,4), 9); np.fill_diagonal(arr, 0); print(arr) -> Option B
  5. Quick Check:

    Fill then fill_diagonal for custom values [OK]
Quick Trick: Fill full array first, then change diagonal [OK]
Common Mistakes:
  • Filling zeros first then trying to fill diagonal with 9
  • Using wrong shape or 1D array for 2D problem
  • Misusing np.fill_diagonal on 1D arrays

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More NumPy Quizzes