Challenge - 5 Problems
Sparse Matrix Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2: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)
Attempts:
2 left
💡 Hint
Remember that COO matrix stores data in the order you provide the row and column indices.
✗ Incorrect
The COO sparse matrix stores the data, row, and column arrays exactly as given. So the printed arrays match the input arrays without reordering.
❓ data_output
intermediate2: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)
Attempts:
2 left
💡 Hint
The nnz attribute gives the count of stored non-zero elements.
✗ Incorrect
The nnz attribute of a CSR matrix returns the number of stored non-zero elements, which is 4 here.
❓ visualization
advanced2: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]])
Attempts:
2 left
💡 Hint
Use the function designed to visualize sparse matrix structure.
✗ Incorrect
plt.spy is the correct function to visualize the sparsity pattern of a sparse matrix.
🧠 Conceptual
advanced2: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?
Attempts:
2 left
💡 Hint
Think about fast row slicing and compact storage of row pointers.
✗ Incorrect
CSR format stores row pointers compactly and is efficient for matrices with many rows and few non-zero elements per row.
🔧 Debug
expert2: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))
Attempts:
2 left
💡 Hint
Check if the lengths of values and column indices match.
✗ Incorrect
The values array length (3) does not match the column indices length (2), causing a ValueError.