0
0
SciPydata~20 mins

Sparse direct solvers (spsolve) in SciPy - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Sparse Solver Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of sparse linear system solution
What is the output of the following code that solves a sparse linear system using spsolve?
SciPy
import numpy as np
from scipy.sparse import csc_matrix
from scipy.sparse.linalg import spsolve

A = csc_matrix([[3, 0, 0], [0, 4, 0], [0, 0, 5]])
b = np.array([3, 8, 10])
x = spsolve(A, b)
print(x)
A[0.33333333 0.5 0.2]
B[9. 32. 50.]
C[1. 2. 2.]
DRaises a ValueError
Attempts:
2 left
💡 Hint
Remember that spsolve solves Ax = b for x.
🧠 Conceptual
intermediate
1:30remaining
Understanding spsolve input requirements
Which of the following statements about the inputs to spsolve is TRUE?
AThe matrix A must be a sparse matrix format supported by SciPy, like CSC or CSR.
BThe vector b must be a sparse matrix.
CThe vector b can be a list or a NumPy array.
DThe matrix A must be a dense NumPy array.
Attempts:
2 left
💡 Hint
Check the documentation for the expected matrix type for A.
🔧 Debug
advanced
2:00remaining
Identify the error in sparse solver usage
What error will the following code raise when executed?
SciPy
import numpy as np
from scipy.sparse import csr_matrix
from scipy.sparse.linalg import spsolve

A = csr_matrix([[1, 2], [3, 4], [5, 6]])
b = np.array([7, 8])
x = spsolve(A, b)
print(x)
AValueError: dimension mismatch between A and b
BTypeError: unsupported operand type(s)
CNo error, outputs solution vector
DLinAlgError: singular matrix
Attempts:
2 left
💡 Hint
Check the shapes of A and b before solving.
data_output
advanced
2:00remaining
Resulting vector from sparse system with zero entries
Given the sparse matrix and vector below, what is the output vector after solving with spsolve?
SciPy
import numpy as np
from scipy.sparse import csc_matrix
from scipy.sparse.linalg import spsolve

A = csc_matrix([[10, 0, 0], [0, 0, 0], [0, 0, 5]])
b = np.array([20, 0, 15])
x = spsolve(A, b)
print(x)
A[20.0, 0.0, 15.0]
B[2.0, 0.0, 3.0]
C[2.0, nan, 3.0]
DRaises a LinAlgError due to singular matrix
Attempts:
2 left
💡 Hint
Check if the matrix A is invertible.
🚀 Application
expert
3:00remaining
Using spsolve for a large sparse system
You have a large sparse matrix A of size 10000x10000 with mostly zeros and a vector b of length 10000. Which approach is MOST efficient to solve Ax = b using SciPy?
AConvert A to a dense NumPy array and use numpy.linalg.solve
BUse scipy.sparse.linalg.spsolve directly on the sparse matrix A and vector b
CConvert b to a sparse matrix and use spsolve
DUse a for-loop to solve each equation separately
Attempts:
2 left
💡 Hint
Consider memory and computation time for large sparse matrices.