Mini Project: An Equation Solver
In this project you will build a small equation solver in plain Python, step by step. It reads an equation typed as text, like x² = 5x - 6, turns it into exact coefficients, solves linear and quadratic equations with Fraction and the quadratic formula (including irrational and complex roots, written exactly), checks every answer against SymPy, and finally solves 2×2 and 3×3 systems of linear equations.
What we are building: a solve("...") function that prints answers like x = 3/2 ± 1/2·√5 or x = -1 ± 2i, a test run that compares it with SymPy on a list of equations, and a solve_system([...]) function for systems.
| Step | New concepts |
|---|---|
| 1. Read one side | regular expressions, terms, Fraction coefficients |
| 2. Read a whole equation | moving everything to one side, the standard form |
| 3. Linear equations | exact solving, identities and contradictions |
| 4. Quadratic equations | the discriminant, simplified square roots, complex roots |
| 5. Check against SymPy | an independent solver as a test oracle |
| 6. Systems of equations | Gauss–Jordan elimination with fractions, unique / none / infinitely many |
It uses ideas from translating equations, combining like terms, the quadratic formula, the discriminant, simplifying radicals and the matrix method.
Note: Every step is a complete program, so each block repeats the functions from the steps before it. Copy one block into your own editor and keep growing it.
Step 1: Read one side
An expression like 3x^2 - 4x + 1 is a sum of terms. Each term is an optional sign, an optional number (integer, decimal or fraction like 1/2) and an optional x with an optional power. Two tricks make it easy to split: replace every - with +-, so splitting on + keeps the signs, and normalise x² and x**2 to x^2. A regular expression then reads one term at a time. Coefficients are stored in a dictionary from power to Fraction, and like terms are combined as they arrive.
import re
from fractions import Fraction as F
TERM = re.compile(r"([+-]?)(\d+(?:\.\d+)?(?:/\d+)?)?\*?(x(?:\^(\d+))?)?")
def parse_side(text):
"""'3x^2 - 4x + 1' -> {2: 3, 1: -4, 0: 1} with Fraction coefficients."""
s = text.replace(" ", "").replace("**", "^").replace("²", "^2").replace("-", "+-")
poly = {}
for term in s.split("+"):
if not term:
continue
m = TERM.fullmatch(term)
if not m or (m.group(2) is None and m.group(3) is None):
raise ValueError(f"cannot read term {term!r}")
sign, num, xpart, power = m.groups()
coef = F(num) if num else F(1)
k = int(power or 1) if xpart else 0
poly[k] = poly.get(k, 0) + (-coef if sign == "-" else coef)
return poly
for text in ["3x^2 - 4x + 1", "-x² + 1/2x", "0.5x - 2.25 + x", "7", "2*x**2 - x^2"]:
poly = parse_side(text)
shown = {k: str(v) for k, v in sorted(poly.items(), reverse=True)}
print(f"{text:16} -> {shown}")
try:
parse_side("3y + 1")
except ValueError as e:
print("error:", e)3x^2 - 4x + 1 -> {2: '3', 1: '-4', 0: '1'}
-x² + 1/2x -> {2: '-1', 1: '1/2'}
0.5x - 2.25 + x -> {1: '3/2', 0: '-9/4'}
7 -> {0: '7'}
2*x**2 - x^2 -> {2: '1'}
error: cannot read term '3y'
Fraction("0.5") is exactly and Fraction("2.25") is , so decimals typed by the user stay exact. 0.5x + x became by combining like terms.
Step 2: Read a whole equation
An equation is two sides. Subtracting the right side from the left gives the standard form (see defining quadratic equations). Terms of higher degree are rejected for now. A small show function prints the standard form, so the user can see how the solver understood the input.
import re
from fractions import Fraction as F
TERM = re.compile(r"([+-]?)(\d+(?:\.\d+)?(?:/\d+)?)?\*?(x(?:\^(\d+))?)?")
def parse_side(text):
"""'3x^2 - 4x + 1' -> {2: 3, 1: -4, 0: 1} with Fraction coefficients."""
s = text.replace(" ", "").replace("**", "^").replace("²", "^2").replace("-", "+-")
poly = {}
for term in s.split("+"):
if not term:
continue
m = TERM.fullmatch(term)
if not m or (m.group(2) is None and m.group(3) is None):
raise ValueError(f"cannot read term {term!r}")
sign, num, xpart, power = m.groups()
coef = F(num) if num else F(1)
k = int(power or 1) if xpart else 0
poly[k] = poly.get(k, 0) + (-coef if sign == "-" else coef)
return poly
def parse_equation(text):
"""'x² = 5x - 6' -> (a, b, c) of a·x² + b·x + c = 0."""
if text.count("=") != 1:
raise ValueError("need exactly one '='")
left, right = (parse_side(s) for s in text.split("="))
poly = {k: left.get(k, 0) - right.get(k, 0) for k in set(left) | set(right)}
if any(k > 2 and v != 0 for k, v in poly.items()):
raise ValueError("only linear and quadratic equations")
return poly.get(2, F(0)), poly.get(1, F(0)), poly.get(0, F(0))
def show(a, b, c):
out = ""
for coef, sym in ((a, "x²"), (b, "x"), (c, "")):
if coef == 0:
continue
mag = abs(coef)
body = (str(mag) if mag != 1 or not sym else "") + sym
out += (" - " if coef < 0 else " + ") + body if out else ("-" if coef < 0 else "") + body
return (out or "0") + " = 0"
for text in ["3x - 7 = 2x + 5", "x² = 5x - 6", "1/2x^2 + x = 4", "x + 1 = x + 1", "2x = 2x + 3"]:
print(f"{text:16} -> {show(*parse_equation(text))}")3x - 7 = 2x + 5 -> x - 12 = 0
x² = 5x - 6 -> x² - 5x + 6 = 0
1/2x^2 + x = 4 -> 1/2x² + x - 4 = 0
x + 1 = x + 1 -> 0 = 0
2x = 2x + 3 -> -3 = 0
Two special cases already show up: x + 1 = x + 1 collapses to (true for every ), and 2x = 2x + 3 to (never true).
Step 3: Linear equations
When , the equation is and the answer is (equations with one unknown). If is also 0, there is no to solve for: either the equation is an identity () or a contradiction. The solver returns both a human-readable string and the list of roots, which the tests in Step 5 will use.
import re
from fractions import Fraction as F
TERM = re.compile(r"([+-]?)(\d+(?:\.\d+)?(?:/\d+)?)?\*?(x(?:\^(\d+))?)?")
def parse_side(text):
"""'3x^2 - 4x + 1' -> {2: 3, 1: -4, 0: 1} with Fraction coefficients."""
s = text.replace(" ", "").replace("**", "^").replace("²", "^2").replace("-", "+-")
poly = {}
for term in s.split("+"):
if not term:
continue
m = TERM.fullmatch(term)
if not m or (m.group(2) is None and m.group(3) is None):
raise ValueError(f"cannot read term {term!r}")
sign, num, xpart, power = m.groups()
coef = F(num) if num else F(1)
k = int(power or 1) if xpart else 0
poly[k] = poly.get(k, 0) + (-coef if sign == "-" else coef)
return poly
def parse_equation(text):
"""'x² = 5x - 6' -> (a, b, c) of a·x² + b·x + c = 0."""
if text.count("=") != 1:
raise ValueError("need exactly one '='")
left, right = (parse_side(s) for s in text.split("="))
poly = {k: left.get(k, 0) - right.get(k, 0) for k in set(left) | set(right)}
if any(k > 2 and v != 0 for k, v in poly.items()):
raise ValueError("only linear and quadratic equations")
return poly.get(2, F(0)), poly.get(1, F(0)), poly.get(0, F(0))
def solve_linear(b, c):
if b == 0:
return ("every x", []) if c == 0 else ("no solution", [])
x = -c / b
return f"x = {x}", [x]
for text in ["3x - 7 = 2x + 5", "0.2x + 1.5 = 0.7x - 1", "1/3x + 1/4 = 1/2", "x + 1 = x + 1", "2x = 2x + 3"]:
a, b, c = parse_equation(text)
answer, roots = solve_linear(b, c)
print(f"{text:22} {answer}")3x - 7 = 2x + 5 x = 12
0.2x + 1.5 = 0.7x - 1 x = 5
1/3x + 1/4 = 1/2 x = 3/4
x + 1 = x + 1 every x
2x = 2x + 3 no solution
With floats, gives , because is not exactly 0.5 in binary; with fractions it is exactly 5.
Step 4: Quadratic equations
For , use the quadratic formula with the discriminant . Because , and are fractions, is an exact fraction, and three cases follow:
To write exactly, sqrt_parts uses and pulls the largest square factor out of the integer , the same way is simplified by hand. Each answer also carries float (or complex) values for testing.
import re
from fractions import Fraction as F
TERM = re.compile(r"([+-]?)(\d+(?:\.\d+)?(?:/\d+)?)?\*?(x(?:\^(\d+))?)?")
def parse_side(text):
"""'3x^2 - 4x + 1' -> {2: 3, 1: -4, 0: 1} with Fraction coefficients."""
s = text.replace(" ", "").replace("**", "^").replace("²", "^2").replace("-", "+-")
poly = {}
for term in s.split("+"):
if not term:
continue
m = TERM.fullmatch(term)
if not m or (m.group(2) is None and m.group(3) is None):
raise ValueError(f"cannot read term {term!r}")
sign, num, xpart, power = m.groups()
coef = F(num) if num else F(1)
k = int(power or 1) if xpart else 0
poly[k] = poly.get(k, 0) + (-coef if sign == "-" else coef)
return poly
def parse_equation(text):
"""'x² = 5x - 6' -> (a, b, c) of a·x² + b·x + c = 0."""
if text.count("=") != 1:
raise ValueError("need exactly one '='")
left, right = (parse_side(s) for s in text.split("="))
poly = {k: left.get(k, 0) - right.get(k, 0) for k in set(left) | set(right)}
if any(k > 2 and v != 0 for k, v in poly.items()):
raise ValueError("only linear and quadratic equations")
return poly.get(2, F(0)), poly.get(1, F(0)), poly.get(0, F(0))
def solve_linear(b, c):
if b == 0:
return ("every x", []) if c == 0 else ("no solution", [])
x = -c / b
return f"x = {x}", [x]
def sqrt_parts(d):
"""√d = k·√m for a Fraction d > 0: k a Fraction, m a square-free integer."""
n, k, f = d.numerator * d.denominator, 1, 2 # √(p/q) = √(p·q) / q
while f * f <= n:
while n % (f * f) == 0:
n //= f * f
k *= f
f += 1
return F(k, d.denominator), n
def surd(k, m):
if m == 1:
return str(k)
return f"√{m}" if k == 1 else f"{k}·√{m}"
def solve(text):
a, b, c = parse_equation(text)
if a == 0:
return solve_linear(b, c)
d = b * b - 4 * a * c # the discriminant, exact
centre = -b / (2 * a)
if d == 0:
return f"x = {centre} (double root)", [centre]
k, m = sqrt_parts(abs(d))
k = k / abs(2 * a) # √|d| / |2a| = k·√m
s = float(k) * m ** 0.5
if d > 0 and m == 1:
return f"x = {centre - k} or x = {centre + k}", [centre - k, centre + k]
lead = f"x = {centre} ± " if centre != 0 else "x = ± "
if d > 0:
return lead + surd(k, m), [float(centre) - s, float(centre) + s]
imag = ("" if k == 1 else str(k)) + "i" if m == 1 else surd(k, m) + "·i"
return lead + imag, [complex(centre, -s), complex(centre, s)]
for text in ["2x^2 - 3x + 1 = 0", "x² = 5x - 6", "x^2 - 3x + 1 = 0", "x^2 = 8",
"x^2 + 2x + 5 = 0", "x^2 + 2 = 2x", "9x^2 - 12x + 4 = 0", "1/2x^2 + x = 4"]:
print(f"{text:20} {solve(text)[0]}")2x^2 - 3x + 1 = 0 x = 1/2 or x = 1
x² = 5x - 6 x = 2 or x = 3
x^2 - 3x + 1 = 0 x = 3/2 ± 1/2·√5
x^2 = 8 x = ± 2·√2
x^2 + 2x + 5 = 0 x = -1 ± 2i
x^2 + 2 = 2x x = 1 ± i
9x^2 - 12x + 4 = 0 x = 2/3 (double root)
1/2x^2 + x = 4 x = -4 or x = 2
Read one by hand: for , , so , printed as 1/2·√5. For , the standard form is , , and .
Step 5: Check against SymPy
A solver is only trustworthy if it is tested. SymPy is a completely separate implementation, which makes it a good test oracle: parse the same text with SymPy's own parser (with implicit multiplication, so 2x means 2*x, and ^ as power), let sp.solve find the roots, and compare numerically with a small tolerance. The identity case needs special care: SymPy reduces it to the expression 0.
import re
from fractions import Fraction as F
TERM = re.compile(r"([+-]?)(\d+(?:\.\d+)?(?:/\d+)?)?\*?(x(?:\^(\d+))?)?")
def parse_side(text):
"""'3x^2 - 4x + 1' -> {2: 3, 1: -4, 0: 1} with Fraction coefficients."""
s = text.replace(" ", "").replace("**", "^").replace("²", "^2").replace("-", "+-")
poly = {}
for term in s.split("+"):
if not term:
continue
m = TERM.fullmatch(term)
if not m or (m.group(2) is None and m.group(3) is None):
raise ValueError(f"cannot read term {term!r}")
sign, num, xpart, power = m.groups()
coef = F(num) if num else F(1)
k = int(power or 1) if xpart else 0
poly[k] = poly.get(k, 0) + (-coef if sign == "-" else coef)
return poly
def parse_equation(text):
"""'x² = 5x - 6' -> (a, b, c) of a·x² + b·x + c = 0."""
if text.count("=") != 1:
raise ValueError("need exactly one '='")
left, right = (parse_side(s) for s in text.split("="))
poly = {k: left.get(k, 0) - right.get(k, 0) for k in set(left) | set(right)}
if any(k > 2 and v != 0 for k, v in poly.items()):
raise ValueError("only linear and quadratic equations")
return poly.get(2, F(0)), poly.get(1, F(0)), poly.get(0, F(0))
def solve_linear(b, c):
if b == 0:
return ("every x", []) if c == 0 else ("no solution", [])
x = -c / b
return f"x = {x}", [x]
def sqrt_parts(d):
"""√d = k·√m for a Fraction d > 0: k a Fraction, m a square-free integer."""
n, k, f = d.numerator * d.denominator, 1, 2 # √(p/q) = √(p·q) / q
while f * f <= n:
while n % (f * f) == 0:
n //= f * f
k *= f
f += 1
return F(k, d.denominator), n
def surd(k, m):
if m == 1:
return str(k)
return f"√{m}" if k == 1 else f"{k}·√{m}"
def solve(text):
a, b, c = parse_equation(text)
if a == 0:
return solve_linear(b, c)
d = b * b - 4 * a * c # the discriminant, exact
centre = -b / (2 * a)
if d == 0:
return f"x = {centre} (double root)", [centre]
k, m = sqrt_parts(abs(d))
k = k / abs(2 * a) # √|d| / |2a| = k·√m
s = float(k) * m ** 0.5
if d > 0 and m == 1:
return f"x = {centre - k} or x = {centre + k}", [centre - k, centre + k]
lead = f"x = {centre} ± " if centre != 0 else "x = ± "
if d > 0:
return lead + surd(k, m), [float(centre) - s, float(centre) + s]
imag = ("" if k == 1 else str(k)) + "i" if m == 1 else surd(k, m) + "·i"
return lead + imag, [complex(centre, -s), complex(centre, s)]
import sympy as sp
from sympy.parsing.sympy_parser import (parse_expr, standard_transformations,
implicit_multiplication_application, convert_xor)
TR = standard_transformations + (implicit_multiplication_application, convert_xor)
x = sp.symbols("x")
def sympy_check(text, roots):
left, right = (parse_expr(s.replace("²", "^2"), transformations=TR, local_dict={"x": x})
for s in text.split("="))
expr = sp.expand(left - right)
if expr == 0:
return roots == [] # identity: we report "every x"
theirs = sorted((complex(r) for r in sp.solve(expr, x)), key=lambda z: (z.real, z.imag))
mine = sorted((complex(r) for r in roots), key=lambda z: (z.real, z.imag))
return len(mine) == len(theirs) and all(abs(p - q) < 1e-12 for p, q in zip(mine, theirs))
tests = ["3x - 7 = 2x + 5", "0.2x + 1.5 = 0.7x - 1", "2x^2 - 3x + 1 = 0", "x² = 5x - 6",
"x^2 - 3x + 1 = 0", "x^2 + 2x + 5 = 0", "3x^2 + 2x + 1 = 0", "9x^2 - 12x + 4 = 0",
"1/2x^2 + x = 4", "x + 1 = x + 1", "2x = 2x + 3"]
passed = 0
for text in tests:
answer, roots = solve(text)
ok = sympy_check(text, roots)
passed += ok
print(f"{'PASS' if ok else 'FAIL'} {text:22} {answer}")
print(f"{passed}/{len(tests)} agree with SymPy")PASS 3x - 7 = 2x + 5 x = 12
PASS 0.2x + 1.5 = 0.7x - 1 x = 5
PASS 2x^2 - 3x + 1 = 0 x = 1/2 or x = 1
PASS x² = 5x - 6 x = 2 or x = 3
PASS x^2 - 3x + 1 = 0 x = 3/2 ± 1/2·√5
PASS x^2 + 2x + 5 = 0 x = -1 ± 2i
PASS 3x^2 + 2x + 1 = 0 x = -1/3 ± 1/3·√2·i
PASS 9x^2 - 12x + 4 = 0 x = 2/3 (double root)
PASS 1/2x^2 + x = 4 x = -4 or x = 2
PASS x + 1 = x + 1 every x
PASS 2x = 2x + 3 no solution
11/11 agree with SymPy
Tip: Try breaking it. Change
centre - ktocentre + kinsolveand rerun: the SymPy check catches the bug at once. Tests that compare against an independent method are one of the most useful habits in numeric code.
Step 6: Systems of equations
Now several unknowns. Each equation like 2x + 3y = 12 is read into one row of an augmented matrix [coefficients | constant], using the same term trick with any single-letter variable. Then Gauss–Jordan elimination with fractions (the matrix method): for each column, find a row with a non-zero entry (the pivot), scale it to 1, and clear that column from every other row. At the end:
- a row with means no solution (inconsistent);
- fewer pivots than unknowns means infinitely many solutions (a free variable);
- otherwise each pivot row reads off one unknown.
import re
from fractions import Fraction as F
import sympy as sp
TERM = re.compile(r"([+-]?)(\d+(?:\.\d+)?(?:/\d+)?)?\*?([a-z])?")
def parse_linear(text, names):
row, const = {v: F(0) for v in names}, F(0)
left, right = text.split("=")
for side, side_sign in ((left, 1), (right, -1)):
for term in side.replace(" ", "").replace("-", "+-").split("+"):
if not term:
continue
m = TERM.fullmatch(term)
if not m or (m.group(2) is None and m.group(3) is None) or (m.group(3) and m.group(3) not in names):
raise ValueError(f"cannot read term {term!r}")
sign, num, var = m.groups()
coef = (F(num) if num else F(1)) * (-1 if sign == "-" else 1) * side_sign
if var:
row[var] += coef
else:
const -= coef # constants go to the right side
return [row[v] for v in names] + [const]
def solve_system(equations, names):
M = [parse_linear(e, names) for e in equations]
n, pivots, r = len(names), [], 0
for col in range(n):
p = next((i for i in range(r, len(M)) if M[i][col] != 0), None)
if p is None:
continue # no pivot: a free variable
M[r], M[p] = M[p], M[r]
M[r] = [v / M[r][col] for v in M[r]]
for i in range(len(M)):
if i != r and M[i][col] != 0:
f = M[i][col]
M[i] = [a - f * b for a, b in zip(M[i], M[r])]
pivots.append(col)
r += 1
if any(all(v == 0 for v in row[:n]) and row[n] != 0 for row in M):
return "no solution", {}
if len(pivots) < n:
return "infinitely many solutions", {}
return "unique", {names[c]: M[i][n] for i, c in enumerate(pivots)}
def sympy_system(equations, names):
syms = sp.symbols(" ".join(names))
star = lambda s: sp.sympify(re.sub(r"(\d)([a-z])", r"\1*\2", s))
return sp.linsolve([star(l) - star(r) for l, r in (e.split("=") for e in equations)], *syms)
systems = [(["2x + 3y = 12", "x - y = 1"], "xy"),
(["x + y + z = 6", "2x - y + z = 3", "x + 2y - z = 2"], "xyz"),
(["1/2x + 1/3y = 2", "x - y = -1"], "xy"),
(["3x + 2y - z = 1", "2x - 2y + 4z = -2", "-x + 1/2y - z = 0"], "xyz"),
(["x + 2y = 4", "2x + 4y = 8"], "xy"),
(["x + 2y = 4", "2x + 4y = 9"], "xy")]
for eqs, names in systems:
kind, sol = solve_system(eqs, names)
shown = ", ".join(f"{k} = {v}" for k, v in sol.items())
print(f"{' ; '.join(eqs)}\n {kind} {shown} SymPy: {sympy_system(eqs, names)}")2x + 3y = 12 ; x - y = 1
unique x = 3, y = 2 SymPy: {(3, 2)}
x + y + z = 6 ; 2x - y + z = 3 ; x + 2y - z = 2
unique x = 1, y = 2, z = 3 SymPy: {(1, 2, 3)}
1/2x + 1/3y = 2 ; x - y = -1
unique x = 2, y = 3 SymPy: {(2, 3)}
3x + 2y - z = 1 ; 2x - 2y + 4z = -2 ; -x + 1/2y - z = 0
unique x = 1, y = -2, z = -2 SymPy: {(1, -2, -2)}
x + 2y = 4 ; 2x + 4y = 8
infinitely many solutions SymPy: {(4 - 2*y, y)}
x + 2y = 4 ; 2x + 4y = 9
no solution SymPy: EmptySet
Every unique solution matches SymPy's linsolve. For the dependent pair (the second equation is twice the first), SymPy describes the infinite family as ; for the contradictory pair it returns the empty set, exactly as our solver classified them. The determinant view of the same question is in Cramer's rule, and the general theory in Gaussian elimination.
Ideas to extend it
- Accept brackets such as
2(x - 3) = 4by expanding them first (hint: a tiny recursive parser, or SymPy'sexpandas a pre-step). - Print the infinite family yourself: express each pivot variable in terms of the free ones.
- Show the working: print , and each step of the formula, like a worked solution.
- Add cubic equations by trying rational roots ( divides , divides ), then dividing out with Horner's method and solving the remaining quadratic.
Test yourself
Why does the parser replace '-' with '+-' before splitting on '+'?
- To make every number positive
- So each piece keeps its own sign after the split
- Because regular expressions cannot match '-'
- To remove subtraction from the equation
The solver gets for a quadratic with . How does sqrt_parts write ?
- Not possible exactly
After Gauss–Jordan elimination one row reads 0 0 | 1. What does the solver report?
- A unique solution
- Infinitely many solutions
- No solution