Bird
0
0

Which code snippet correctly does this?

hard📝 Application Q15 of 15
SciPy - Integration with Scientific Ecosystem
You have a large sparse matrix stored in large_matrix.npz. You want to load it, add 5 to all non-zero elements, and save it back without converting to a dense matrix (to save memory). Which code snippet correctly does this?
Afrom scipy.sparse import load_npz, save_npz mat = load_npz('large_matrix.npz') mat.data += 5 save_npz('large_matrix.npz', mat)
Bfrom scipy.sparse import load_npz, save_npz mat = load_npz('large_matrix.npz') mat = mat.toarray() + 5 save_npz('large_matrix.npz', mat)
Cimport numpy as np mat = np.load('large_matrix.npz') mat += 5 np.save('large_matrix.npz', mat)
Dfrom scipy.sparse import load_npz, save_npz mat = load_npz('large_matrix.npz') mat.toarray() += 5 save_npz('large_matrix.npz', mat)
Step-by-Step Solution
Solution:
  1. Step 1: Load sparse matrix and modify non-zero elements

    Using mat.data accesses the non-zero values directly. Adding 5 to mat.data updates only those values without converting to dense.
  2. Step 2: Save the updated sparse matrix back

    Using save_npz saves the modified sparse matrix efficiently.
  3. Step 3: Check other options for correctness

    from scipy.sparse import load_npz, save_npz mat = load_npz('large_matrix.npz') mat = mat.toarray() + 5 save_npz('large_matrix.npz', mat) converts to dense explicitly, adds 5 to all elements including zeros, wastes memory, and save_npz fails on dense array. import numpy as np mat = np.load('large_matrix.npz') mat += 5 np.save('large_matrix.npz', mat) uses numpy load/save which does not handle sparse matrices. from scipy.sparse import load_npz, save_npz mat = load_npz('large_matrix.npz') mat.toarray() += 5 save_npz('large_matrix.npz', mat) tries to add 5 to a dense array but does not assign back, and wastes memory.
  4. Final Answer:

    from scipy.sparse import load_npz, save_npz mat = load_npz('large_matrix.npz') mat.data += 5 save_npz('large_matrix.npz', mat) -> Option A
  5. Quick Check:

    Modify mat.data for sparse update [OK]
Quick Trick: Change mat.data to update non-zero sparse values [OK]
Common Mistakes:
  • Adding scalar directly to sparse matrix (converts to dense)
  • Using numpy load/save for sparse matrices
  • Modifying dense array without saving changes

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More SciPy Quizzes