Bird
0
0

Consider the following code snippet:

medium📝 Predict Output Q13 of 15
SciPy - Integration with Scientific Ecosystem
Consider the following code snippet:
from scipy.sparse import csr_matrix, save_npz, load_npz
import numpy as np

arr = np.array([[0, 0, 1], [1, 0, 0], [0, 2, 0]])
sp = csr_matrix(arr)
save_npz('matrix.npz', sp)
loaded_sp = load_npz('matrix.npz')
print(loaded_sp.toarray())

What will be the output printed?
AError: cannot convert sparse matrix to array
B[[0 0 0] [0 0 0] [0 0 0]]
C[[0 0 1] [1 0 0] [0 2 0]]
D[[1 0 0] [0 1 0] [0 0 1]]
Step-by-Step Solution
Solution:
  1. Step 1: Create sparse matrix and save it

    The code creates a sparse matrix from the numpy array, saves it to 'matrix.npz', then loads it back.
  2. Step 2: Convert loaded sparse matrix to dense array and print

    Using toarray() converts the sparse matrix back to the original dense numpy array, so the printed output matches the original array.
  3. Final Answer:

    [[0 0 1] [1 0 0] [0 2 0]] -> Option C
  4. Quick Check:

    load_npz + toarray() = original array [OK]
Quick Trick: load_npz returns sparse; use toarray() to see full matrix [OK]
Common Mistakes:
  • Expecting zeros after loading
  • Forgetting to convert sparse to dense before printing
  • Confusing save_npz and load_npz usage

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More SciPy Quizzes