Algebra Exercises
Time to practise across the whole course: translating words into equations, simplifying, inequalities, factoring, polynomial division, rational equations, quadratics, systems, lines and exponential equations. Each exercise has a starter program that runs but does not do the job yet. Replace the TODO parts, press ▶ Run, and compare your result with the expected output. The output block under each starter shows what the unfinished starter prints.
Tip: Solve each problem on paper first, then let the code confirm it. When the two disagree, finding out which one is wrong is the real exercise.
| # | Exercise | Practises |
|---|---|---|
| 1 | The phone bill | translating words, one-unknown equations |
| 2 | Expand and simplify | removing parentheses, like terms |
| 3 | Integers in a range | compound inequalities |
| 4 | Factor by the ac method | factoring |
| 5 | Long division | dividing polynomials |
| 6 | The fake solution | rational equations |
| 7 | Classify the roots | the discriminant, quadratic formula |
| 8 | Cramer's rule, exactly | 3×3 determinants |
| 9 | A line through two points | slope, equations of lines |
| 10 | Fading out | exponential equations |
Exercise 1: The phone bill
A phone plan costs 12.00 per month plus 0.05 per MB of data. This month's bill was 19.50. Write the equation and solve it exactly with Fraction (no floats), then check it.
from fractions import Fraction as F
base, per_mb, bill = F("12.00"), F("0.05"), F("19.50")
m = F(0) # TODO: solve base + per_mb * m = bill for m
print("MB used:", m)
print("check:", base + per_mb * m == bill)MB used: 0
check: False
Expected output when solved:
MB used: 150
check: TrueHint: Undo the operations in reverse order: subtract the base, then divide by the price per MB.
Show solution
from fractions import Fraction as F
base, per_mb, bill = F("12.00"), F("0.05"), F("19.50")
m = (bill - base) / per_mb
print("MB used:", m)
print("check:", base + per_mb * m == bill)MB used: 150
check: True
7.50 of the bill is data, and . Fraction("0.05") is exactly , so the check uses exact equality safely.
Exercise 2: Expand and simplify
Simplify by hand and type your result as by_hand. The program compares it with SymPy's expansion and at a few values of .
import sympy as sp
x = sp.symbols("x")
expr = 3*(2*x - 4) - 2*(x - 5) + x*(x + 1)
by_hand = 0 * x # TODO: your simplified expression
print("SymPy :", sp.expand(expr))
print("by hand:", by_hand)
print("equal :", sp.expand(expr - by_hand) == 0)SymPy : x**2 + 5*x - 2
by hand: 0
equal : False
Expected output when solved: the "by hand" line shows x**2 + 5*x - 2 and equal : True.
Hint: : the minus sign multiplies both terms.
Show solution
import sympy as sp
x = sp.symbols("x")
expr = 3*(2*x - 4) - 2*(x - 5) + x*(x + 1)
by_hand = x**2 + 5*x - 2
print("SymPy :", sp.expand(expr))
print("by hand:", by_hand)
print("equal :", sp.expand(expr - by_hand) == 0)SymPy : x**2 + 5*x - 2
by hand: x**2 + 5*x - 2
equal : True
Exercise 3: Integers in a range
Solve by hand, then fill in low and high so that the program lists all integer solutions, and confirm with a brute-force check over .
low, high = 0, 0 # TODO: the solution is low <= x < high
from_algebra = [x for x in range(low, high)]
brute_force = [x for x in range(-10, 11) if -3 <= 2 * x + 1 < 9]
print(from_algebra)
print(brute_force)
print(from_algebra == brute_force)[]
[-2, -1, 0, 1, 2, 3]
False
Expected output when solved: both lists are [-2, -1, 0, 1, 2, 3] and the last line is True.
Hint: Do the same thing to all three parts: subtract 1, then divide by 2.
Show solution
low, high = -2, 4
from_algebra = [x for x in range(low, high)]
brute_force = [x for x in range(-10, 11) if -3 <= 2 * x + 1 < 9]
print(from_algebra)
print(brute_force)
print(from_algebra == brute_force)[-2, -1, 0, 1, 2, 3]
[-2, -1, 0, 1, 2, 3]
True
Exercise 4: Factor by the ac method
To factor , find two integers and with and , then split the middle term and group. Complete find_pair and use it on .
import sympy as sp
def find_pair(a, b, c):
# TODO: return (p, q) with p * q == a * c and p + q == b, or None
return None
print(find_pair(6, 7, -3))
x = sp.symbols("x")
print(sp.factor(6*x**2 + 7*x - 3))None
(2*x + 3)*(3*x - 1)
Expected output when solved:
(-2, 9)
(2*x + 3)*(3*x - 1)Hint: Try every from to ; skip ; must be and divide evenly.
Show solution
import sympy as sp
def find_pair(a, b, c):
ac = a * c
for p in range(-abs(ac), abs(ac) + 1):
if p != 0 and ac % p == 0 and p + ac // p == b:
return (p, ac // p)
return None
print(find_pair(6, 7, -3))
x = sp.symbols("x")
print(sp.factor(6*x**2 + 7*x - 3))(-2, 9)
(2*x + 3)*(3*x - 1)
With and : .
Exercise 5: Long division
Complete poly_divide, which divides polynomials given as coefficient lists (highest power first) and returns the quotient and remainder. Test it on .
def poly_divide(num, den):
num = list(num)
quotient = []
# TODO: repeat while len(num) >= len(den):
# factor = num[0] / den[0]; append it to quotient;
# subtract factor * den from the front of num; drop the leading 0
return quotient, num
q, r = poly_divide([2, 3, 0, -1, 5], [1, 0, 1])
print("quotient :", q)
print("remainder:", r)quotient : []
remainder: [2, 3, 0, -1, 5]
Expected output when solved:
quotient : [2.0, 3.0, -2.0]
remainder: [-4.0, 7.0]That is, quotient and remainder .
Hint: After subtracting, the first coefficient of
numis always 0, sonum.pop(0)removes it.
Show solution
def poly_divide(num, den):
num = list(num)
quotient = []
while len(num) >= len(den):
factor = num[0] / den[0]
quotient.append(factor)
for i in range(len(den)):
num[i] -= factor * den[i]
num.pop(0)
return quotient, num
q, r = poly_divide([2, 3, 0, -1, 5], [1, 0, 1])
print("quotient :", q)
print("remainder:", r)quotient : [2.0, 3.0, -2.0]
remainder: [-4.0, 7.0]
Check: . ✓
Exercise 6: The fake solution
Solve . Multiplying by gives , that is . The starter finds both candidates; add the check that throws out any candidate making a denominator zero.
import sympy as sp
x = sp.symbols("x")
candidates = sp.solve(x**2 - 5*x + 6, x)
print("candidates:", candidates)
valid = candidates # TODO: keep only v with v != 0 and v - 3 != 0
print("solutions :", valid)candidates: [2, 3]
solutions : [2, 3]
Expected output when solved:
candidates: [2, 3]
solutions : [2]Hint: The original denominators are and .
Show solution
import sympy as sp
x = sp.symbols("x")
candidates = sp.solve(x**2 - 5*x + 6, x)
print("candidates:", candidates)
valid = [v for v in candidates if v != 0 and v - 3 != 0]
print("solutions :", valid)candidates: [2, 3]
solutions : [2]
makes zero, so it is extraneous. Check : and . ✓
Exercise 7: Classify the roots
Complete roots so that it returns the kind of roots of and the roots themselves: real roots as floats, complex roots via cmath.sqrt.
import cmath, math
def roots(a, b, c):
d = b * b - 4 * a * c
# TODO: d > 0 -> ("two real", r1, r2); d == 0 -> ("one real", r);
# d < 0 -> ("complex", z1, z2) using cmath.sqrt
return ("?",)
for coeffs in [(1, -5, 6), (4, 4, 1), (1, 2, 5)]:
print(coeffs, roots(*coeffs))(1, -5, 6) ('?',)
(4, 4, 1) ('?',)
(1, 2, 5) ('?',)
Expected output when solved:
(1, -5, 6) ('two real', 2.0, 3.0)
(4, 4, 1) ('one real', -0.5)
(1, 2, 5) ('complex', (-1-2j), (-1+2j))Hint: Return the smaller root first: , then (for ).
Show solution
import cmath, math
def roots(a, b, c):
d = b * b - 4 * a * c
if d > 0:
s = math.sqrt(d)
return ("two real", (-b - s) / (2 * a), (-b + s) / (2 * a))
if d == 0:
return ("one real", -b / (2 * a))
s = cmath.sqrt(d)
return ("complex", (-b - s) / (2 * a), (-b + s) / (2 * a))
for coeffs in [(1, -5, 6), (4, 4, 1), (1, 2, 5)]:
print(coeffs, roots(*coeffs))(1, -5, 6) ('two real', 2.0, 3.0)
(4, 4, 1) ('one real', -0.5)
(1, 2, 5) ('complex', (-1-2j), (-1+2j))
For : , , so .
Exercise 8: Cramer's rule, exactly
Solve , , with Cramer's rule. Complete det3 (the 3×3 determinant by cofactor expansion along the first row); the rest of the program is done.
from fractions import Fraction
def det3(m):
# TODO: a(ei − fh) − b(di − fg) + c(dh − eg)
return 1
A = [[1, 1, 1], [2, -1, 1], [1, 2, -1]]
b = [6, 3, 2]
D = det3(A)
sol = []
for col in range(3):
Ai = [row[:col] + [b[r]] + row[col + 1:] for r, row in enumerate(A)]
sol.append(Fraction(det3(Ai), D))
print("D =", D, " solution:", [str(v) for v in sol])D = 1 solution: ['1', '1', '1']
Expected output when solved:
D = 7 solution: ['1', '2', '3']Hint: Name the entries:
(a, b, c), (d, e, f), (g, h, i) = m.
Show solution
from fractions import Fraction
def det3(m):
(a, b, c), (d, e, f), (g, h, i) = m
return a * (e * i - f * h) - b * (d * i - f * g) + c * (d * h - e * g)
A = [[1, 1, 1], [2, -1, 1], [1, 2, -1]]
b = [6, 3, 2]
D = det3(A)
sol = []
for col in range(3):
Ai = [row[:col] + [b[r]] + row[col + 1:] for r, row in enumerate(A)]
sol.append(Fraction(det3(Ai), D))
print("D =", D, " solution:", [str(v) for v in sol])D = 7 solution: ['1', '2', '3']
. Check: , , . ✓
Exercise 9: A line through two points
Find the line through and in the form , and where it crosses the -axis. Use Fraction so the answers are exact.
from fractions import Fraction as F
(x1, y1), (x2, y2) = (2, 5), (6, -3)
m = F(0) # TODO: slope (y2 − y1) / (x2 − x1)
b = F(0) # TODO: intercept from y1 = m·x1 + b
x_axis = None # TODO: solve m·x + b = 0 (m is not 0 here)
print(f"y = {m}x + {b}, crosses the x-axis at x = {x_axis}")y = 0x + 0, crosses the x-axis at x = None
Expected output when solved:
y = -2x + 9, crosses the x-axis at x = 9/2Hint: .
Show solution
from fractions import Fraction as F
(x1, y1), (x2, y2) = (2, 5), (6, -3)
m = F(y2 - y1, x2 - x1)
b = y1 - m * x1
x_axis = -b / m
print(f"y = {m}x + {b}, crosses the x-axis at x = {x_axis}")y = -2x + 9, crosses the x-axis at x = 9/2
, , and gives .
Exercise 10: Fading out
A sound effect starts at volume 1000 and each frame it is multiplied by 0.8. Find the first frame at which the volume is below 1, first with logarithms (solve ), then with a loop.
import math
n_formula = 0 # TODO: ceil of the solution of 1000 * 0.8**n = 1
n_loop, volume = 0, 1000.0
# TODO: loop: while volume >= 1, multiply by 0.8 and count frames
print("formula:", n_formula, " loop:", n_loop, f" volume then: {volume:.4f}")formula: 0 loop: 0 volume then: 1000.0000
Expected output when solved:
formula: 31 loop: 31 volume then: 0.9904Hint: , so . Round up.
Show solution
import math
n_formula = math.ceil(math.log(1 / 1000) / math.log(0.8))
n_loop, volume = 0, 1000.0
while volume >= 1:
volume *= 0.8
n_loop += 1
print("formula:", n_formula, " loop:", n_loop, f" volume then: {volume:.4f}")formula: 31 loop: 31 volume then: 0.9904
After 30 frames the volume is about 1.24, after 31 about 0.99.
Test yourself
In Exercise 6, why is rejected?
- It does not satisfy
- It makes the denominator zero in the original equation
- Negative numbers are not allowed
- SymPy found it twice
A quadratic has discriminant −16. What are its roots like?
- Two distinct real roots
- One repeated real root
- No roots at all
- Two complex conjugate roots
Cramer's rule gives . What is ?
- A with its first column replaced by the right-hand side
- The inverse of A
- A with its first row removed
- A transposed