0
0
SciPydata~20 mins

Matrix creation and operations in SciPy - Practice Problems & Coding Challenges

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

A = csr_matrix(np.array([[1, 0, 2], [0, 3, 0]]))
B = csr_matrix(np.array([[0, 3], [1, 0], [4, 5]]))
C = A.dot(B)
print(C.toarray())
A
[[8 13]
 [0 0]]
B
[[8 10]
 [3 0]]
C
[[8 13]
 [3 0]]
D
[[8 13]
 [0 3]]
Attempts:
2 left
💡 Hint
Remember that matrix multiplication sums the products of row elements of A with column elements of B.
data_output
intermediate
1:30remaining
Shape and type of a sparse matrix
After running this code, what are the shape and type of the matrix M?
SciPy
from scipy.sparse import lil_matrix

M = lil_matrix((3, 4))
M[1, 2] = 5
M[2, 3] = 10
print(M.shape, type(M))
A(3, 4) <class 'numpy.ndarray'>
B(4, 3) <class 'numpy.ndarray'>
C(4, 3) <class 'scipy.sparse.lil_matrix'>
D(3, 4) <class 'scipy.sparse.lil_matrix'>
Attempts:
2 left
💡 Hint
The shape is set when creating the matrix. The type depends on the sparse format used.
🔧 Debug
advanced
1:30remaining
Identify the error in matrix addition
What error will this code raise when adding two sparse matrices of different shapes?
SciPy
from scipy.sparse import csr_matrix

A = csr_matrix([[1, 2], [3, 4]])
B = csr_matrix([[5, 6, 7], [8, 9, 10]])
C = A + B
AValueError: matrix dimension mismatch
BValueError: matrices are not aligned
CTypeError: unsupported operand type(s) for +
DNo error, addition succeeds
Attempts:
2 left
💡 Hint
Check if the shapes of the matrices are compatible for addition.
visualization
advanced
2:00remaining
Visualizing a sparse matrix
Which option correctly creates a visualization of the nonzero elements of a sparse matrix using matplotlib?
SciPy
import matplotlib.pyplot as plt
from scipy.sparse import coo_matrix

row = [0, 1, 2, 0]
col = [0, 2, 2, 1]
data = [4, 5, 7, 9]
M = coo_matrix((data, (row, col)), shape=(3, 3))

plt.figure()
# Fill in the missing code here
plt.show()
Aplt.spy(M)
Bplt.imshow(M.toarray())
Cplt.scatter(M.row, M.col, s=100, c='red')
Dplt.plot(M.data)
Attempts:
2 left
💡 Hint
Use a function designed to show sparsity patterns.
🧠 Conceptual
expert
2:30remaining
Memory efficiency of sparse matrix formats
Which sparse matrix format is generally most memory efficient for fast arithmetic operations on large, sparse matrices?
ALIL (List of Lists)
BCSR (Compressed Sparse Row)
CCOO (Coordinate format)
DDOK (Dictionary of Keys)
Attempts:
2 left
💡 Hint
Consider which format is optimized for arithmetic and slicing.