Code Explanation:
1. Import SymPy
from sympy import Matrix
We bring in Matrix from SymPy.
This lets us work with exact matrices for solving linear equations.
2. Define the Coefficient Matrix
A = Matrix([[2, -1, 1],
[1, 2, -1],
[3, 1, 1]])
This creates a 3×3 matrix representing the coefficients of
x,y,z.
Each row corresponds to one equation.
So it encodes the system:
2x−y+z=2,x+2y−z=3,3x+y+z=7
3. Define the Constant Vector
b = Matrix([2, 3, 7])
This creates a column vector with the right-hand side constants.
It corresponds to the values after the equals sign in the equations.
4. Solve Using LU Decomposition
print(A.LUsolve(b))
SymPy internally applies LU decomposition (splits A into Lower and Upper triangular matrices).
It then performs forward and backward substitution to solve for
x,y,z.
5. Output in Jupyter
Matrix([[1], [2], [2]])
This is how Jupyter displays the solution.
It means:
x=1,y=2,z=2
The reason it looks like a matrix is because SymPy always returns the solution as a column matrix, not a flat list.
Final Understanding
Matrix([[1], [2], [2]]) = a 3×1 column matrix.
Each row represents one solution value:
First row →
x=1
Second row →
y=2
Third row →
z=2
So, the actual solution is:
(x,y,z)=(1,2,2)
Download Book - 500 Days Python Coding Challenges with Explanation
.png)

0 Comments:
Post a Comment