0
0
SciPydata~20 mins

Creating sparse matrices in SciPy - Practice Exercises

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 COO sparse matrix data arrays
What will be the output of the following code snippet that creates a COO sparse matrix and prints its data, row, and column arrays?
SciPy
from scipy.sparse import coo_matrix
import numpy as np

row = np.array([0, 3, 1, 0])
col = np.array([0, 3, 1, 2])
data = np.array([4, 5, 7, 9])

matrix = coo_matrix((data, (row, col)), shape=(4, 4))
print(matrix.data)
print(matrix.row)
print(matrix.col)
A
[4 9 7 5]
[0 0 1 3]
[0 2 1 3]
B
[9 7 5 4]
[3 1 0 0]
[2 1 3 0]
C
[4 5 7 9]
[0 3 1 0]
[0 3 1 2]
D
[4 5 7 9]
[0 1 2 3]
[0 1 2 3]
Attempts:
2 left
💡 Hint
Remember that COO matrix stores data in the order you provide the row and column indices.
data_output
intermediate
2:00remaining
Number of non-zero elements in CSR matrix
Given the following CSR sparse matrix creation code, how many non-zero elements does the matrix contain?
SciPy
from scipy.sparse import csr_matrix

values = [10, 20, 30, 40]
col_indices = [0, 2, 2, 0]
row_ptr = [0, 2, 3, 4]

csr = csr_matrix((values, col_indices, row_ptr), shape=(3, 3))
print(csr.nnz)
A4
B3
C2
D5
Attempts:
2 left
💡 Hint
The nnz attribute gives the count of stored non-zero elements.
visualization
advanced
2:00remaining
Visualizing a sparse matrix pattern
Which option shows the correct matplotlib visualization code to display the sparsity pattern of a CSR matrix named 'csr'?
SciPy
import matplotlib.pyplot as plt
from scipy.sparse import csr_matrix

csr = csr_matrix([[0, 0, 1], [1, 0, 0], [0, 2, 0]])
A
plt.imshow(csr)
plt.show()
B
plt.spy(csr)
plt.show()
C
plt.plot(csr)
plt.show()
D
plt.scatter(csr)
plt.show()
Attempts:
2 left
💡 Hint
Use the function designed to visualize sparse matrix structure.
🧠 Conceptual
advanced
2:00remaining
Memory efficiency of sparse matrix formats
Which sparse matrix format is generally most memory efficient for matrices with many rows but very few non-zero elements per row?
ACSR (Compressed Sparse Row)
BCSC (Compressed Sparse Column)
CCOO (Coordinate format)
DDOK (Dictionary of Keys)
Attempts:
2 left
💡 Hint
Think about fast row slicing and compact storage of row pointers.
🔧 Debug
expert
2:00remaining
Identify the error in sparse matrix creation
What error will this code raise when trying to create a CSR matrix?
SciPy
from scipy.sparse import csr_matrix

values = [1, 2, 3]
col_indices = [0, 1]
row_ptr = [0, 2, 3]

csr = csr_matrix((values, col_indices, row_ptr), shape=(2, 3))
AIndexError: index out of bounds
BNo error, matrix created successfully
CTypeError: unsupported operand type(s)
DValueError: array length mismatch
Attempts:
2 left
💡 Hint
Check if the lengths of values and column indices match.