0
0
SciPydata~20 mins

CSR format (Compressed Sparse Row) in SciPy - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
CSR Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of CSR matrix multiplication
What is the output of the following code that multiplies two CSR 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).toarray()
print(C)
A
[[0 3 0]
 [1 0 0]
 [0 0 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 CSR matrix multiplication follows normal matrix multiplication rules.
data_output
intermediate
1:00remaining
Number of non-zero elements in CSR matrix
Given the CSR matrix below, how many non-zero elements does it contain?
SciPy
from scipy.sparse import csr_matrix

matrix = csr_matrix([[0, 5, 0], [0, 0, 0], [7, 0, 8]])
print(matrix.nnz)
A3
B2
C4
D5
Attempts:
2 left
💡 Hint
Count all the non-zero values in the matrix.
🔧 Debug
advanced
1:30remaining
Identify the error in CSR matrix creation
What error will this code raise when trying to create a CSR matrix?
SciPy
from scipy.sparse import csr_matrix

# Data and indices lengths mismatch
data = [1, 2, 3]
indices = [0, 2]
indptr = [0, 2, 3]

csr = csr_matrix((data, indices, indptr), shape=(2, 3))
ANo error, matrix created successfully
BValueError: indices and data array must be the same length
CTypeError: unsupported operand type(s)
DIndexError: index out of bounds
Attempts:
2 left
💡 Hint
Check if the lengths of data and indices match.
🧠 Conceptual
advanced
1:30remaining
Understanding CSR matrix components
Which of the following correctly describes the role of the 'indptr' array in a CSR matrix?
A'indptr' stores the cumulative count of non-zero elements per row, marking start and end positions in 'data' and 'indices' arrays for each row.
B'indptr' contains the column indices of non-zero elements.
C'indptr' holds the actual non-zero data values of the matrix.
D'indptr' is used to store the shape of the matrix.
Attempts:
2 left
💡 Hint
Think about how CSR stores rows efficiently.
🚀 Application
expert
2:00remaining
Efficient row slicing in CSR matrix
You want to extract the second row from a large CSR matrix efficiently. Which code snippet correctly extracts the second row as a CSR matrix?
SciPy
from scipy.sparse import csr_matrix

matrix = csr_matrix([[0, 1, 0], [2, 0, 3], [0, 0, 4]])
A
row = matrix[1, :]
print(type(row))
B
row = matrix[1]
print(type(row))
C
row = matrix.getrow(1)
print(type(row))
D
row = matrix.toarray()[1]
print(type(row))
Attempts:
2 left
💡 Hint
Look for a method designed for efficient row extraction in CSR.