0
0
SciPydata~20 mins

Sparse matrix operations in SciPy - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Sparse Matrix Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of sparse matrix multiplication
What is the output of this code that multiplies two sparse matrices?
SciPy
import numpy as np
from scipy.sparse import csr_matrix

A = csr_matrix([[0, 0, 1], [1, 0, 0], [0, 2, 0]])
B = csr_matrix([[1, 0, 0], [0, 3, 0], [4, 0, 0]])

C = A.dot(B)
print(C.toarray())
A
[[0 0 0]
 [1 0 0]
 [0 3 0]]
B
[[0 0 0]
 [0 6 0]
 [4 0 0]]
C
[[4 0 0]
 [0 0 0]
 [0 6 0]]
D
[[4 0 0]
 [1 0 0]
 [0 6 0]]
Attempts:
2 left
💡 Hint
Remember that sparse matrix multiplication follows the same rules as dense matrix multiplication.
data_output
intermediate
1:30remaining
Number of non-zero elements after addition
Given two sparse matrices, what is the number of non-zero elements in their sum?
SciPy
from scipy.sparse import csc_matrix

X = csc_matrix([[0, 5, 0], [0, 0, 0], [7, 0, 0]])
Y = csc_matrix([[0, 0, 3], [0, 0, 0], [0, 0, 0]])

Z = X + Y
print(Z.nnz)
A4
B3
C2
D5
Attempts:
2 left
💡 Hint
Count unique non-zero positions after addition.
🔧 Debug
advanced
1:30remaining
Identify the error in sparse matrix slicing
What error does this code raise when slicing a sparse matrix?
SciPy
from scipy.sparse import lil_matrix

M = lil_matrix((3,3))
M[0, 0] = 1
M[1, 1] = 2

sub = M[0:2, 0:2]
print(sub)
AIndexError: index out of bounds
BTypeError: slicing with step is not supported
CNo error, prints a sparse matrix
DValueError: invalid slice
Attempts:
2 left
💡 Hint
Check if lil_matrix supports slicing.
visualization
advanced
1:30remaining
Visualizing sparsity pattern
Which code snippet correctly visualizes the sparsity pattern of a CSR sparse matrix using matplotlib?
SciPy
import matplotlib.pyplot as plt
from scipy.sparse import csr_matrix

A = csr_matrix([[0, 0, 1], [1, 0, 0], [0, 2, 0]])

# Visualization code here
A
plt.spy(A)
plt.show()
B
plt.scatter(A)
plt.show()
C
plt.plot(A)
plt.show()
D
plt.imshow(A)
plt.show()
Attempts:
2 left
💡 Hint
Use the function designed to show sparsity patterns.
🚀 Application
expert
3:00remaining
Efficient sparse matrix row normalization
Which code snippet correctly normalizes each row of a CSR sparse matrix so that each row sums to 1, without converting to dense format?
SciPy
from scipy.sparse import csr_matrix
import numpy as np

M = csr_matrix([[0, 1, 2], [3, 0, 0], [0, 0, 4]])

# Normalize rows here
A
row_sums = np.array(M.sum(axis=1)).flatten()
row_indices, _ = M.nonzero()
M.data /= row_sums[row_indices]
BM = M / M.sum(axis=1)
C
for i in range(M.shape[0]):
    M[i] = M[i] / M[i].sum()
DM = M.multiply(1 / M.sum(axis=0))
Attempts:
2 left
💡 Hint
Use the sparse matrix data and indices to normalize efficiently.