Basic Math Exercises
Time to practise the whole course in code. Each exercise has a starter program that runs but doesn't 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: Work each problem on paper first, then make the code agree with you. If the two disagree, find out which one is wrong. That is where the learning happens. Try each exercise for ten minutes before you open the solution.
| # | Exercise | Practises |
|---|---|---|
| 1 | Simplify a fraction | GCF, equivalent fractions |
| 2 | Add fractions by hand | LCM, mixed numbers |
| 3 | Sale prices | percent of, percent change |
| 4 | Savings plan | compound interest |
| 5 | Scientific notation | powers of ten, exponent laws |
| 6 | How many digits? | logarithms |
| 7 | Simplify a square root | prime factors, radicals |
| 8 | Class statistics | mean, median, mode, standard deviation |
| 9 | Binary by hand | repeated division, place value |
| 10 | Solve exactly | equations, fractions |
Exercise 1: Simplify a fraction
Write simplify(n, d) that returns the fraction in lowest terms as a pair (n, d). Use the greatest common factor, not the fractions module, and keep the sign on the numerator.
import math
def simplify(n, d):
# TODO: divide both by their GCF; move a negative sign to the numerator
return (n, d)
for n, d in [(18, 24), (35, 49), (-12, 16), (7, -21), (0, 5)]:
print(f"{n}/{d} -> {simplify(n, d)}")18/24 -> (18, 24)
35/49 -> (35, 49)
-12/16 -> (-12, 16)
7/-21 -> (7, -21)
0/5 -> (0, 5)
Expected output when solved:
18/24 -> (3, 4)
35/49 -> (5, 7)
-12/16 -> (-3, 4)
7/-21 -> (-1, 3)
0/5 -> (0, 1)Hint:
math.gcdalways returns a non-negative number, andmath.gcd(0, 5)is 5. Ifdis negative, flip the signs of both.
Solution
import math
def simplify(n, d):
g = math.gcd(n, d)
n, d = n // g, d // g
if d < 0:
n, d = -n, -d
return (n, d)
for n, d in [(18, 24), (35, 49), (-12, 16), (7, -21), (0, 5)]:
print(f"{n}/{d} -> {simplify(n, d)}")18/24 -> (3, 4)
35/49 -> (5, 7)
-12/16 -> (-3, 4)
7/-21 -> (-1, 3)
0/5 -> (0, 1)
Exercise 2: Add fractions by hand
Add two fractions using the least common multiple of the denominators, and print the result both as a simplified fraction and as a mixed number. Check your work with Fraction.
import math
from fractions import Fraction
def add(n1, d1, n2, d2):
# TODO: common denominator = lcm(d1, d2); scale both numerators; simplify
return (0, 1)
def mixed(n, d):
# TODO: whole part and remainder, e.g. 19/12 -> "1 7/12"
return f"{n}/{d}"
for a in [(3, 4, 5, 6), (2, 3, 1, 9), (7, 8, 5, 12)]:
n, d = add(*a)
check = Fraction(a[0], a[1]) + Fraction(a[2], a[3])
print(f"{a[0]}/{a[1]} + {a[2]}/{a[3]} = {n}/{d} = {mixed(n, d)} (Fraction: {check})")3/4 + 5/6 = 0/1 = 0/1 (Fraction: 19/12)
2/3 + 1/9 = 0/1 = 0/1 (Fraction: 7/9)
7/8 + 5/12 = 0/1 = 0/1 (Fraction: 31/24)
Expected output when solved:
3/4 + 5/6 = 19/12 = 1 7/12 (Fraction: 19/12)
2/3 + 1/9 = 7/9 = 7/9 (Fraction: 7/9)
7/8 + 5/12 = 31/24 = 1 7/24 (Fraction: 31/24)Hint: For , , so and .
divmod(19, 12)gives the whole part and the remainder.
Solution
import math
from fractions import Fraction
def add(n1, d1, n2, d2):
d = math.lcm(d1, d2)
n = n1 * (d // d1) + n2 * (d // d2)
g = math.gcd(n, d)
return (n // g, d // g)
def mixed(n, d):
whole, rest = divmod(n, d)
if whole == 0:
return f"{rest}/{d}"
return f"{whole} {rest}/{d}" if rest else str(whole)
for a in [(3, 4, 5, 6), (2, 3, 1, 9), (7, 8, 5, 12)]:
n, d = add(*a)
check = Fraction(a[0], a[1]) + Fraction(a[2], a[3])
print(f"{a[0]}/{a[1]} + {a[2]}/{a[3]} = {n}/{d} = {mixed(n, d)} (Fraction: {check})")3/4 + 5/6 = 19/12 = 1 7/12 (Fraction: 19/12)
2/3 + 1/9 = 7/9 = 7/9 (Fraction: 7/9)
7/8 + 5/12 = 31/24 = 1 7/24 (Fraction: 31/24)
Exercise 3: Sale prices
A shop lowers a €80 jacket by 25%, and a week later raises the sale price by 25%. Compute the sale price, the final price, and the overall percent change from €80. Many people expect it to end at €80 again.
original = 80.0
sale = original # TODO: 25% off
final = sale # TODO: then 25% on top of the sale price
change = 0.0 # TODO: percent change from original to final
print(f"sale price : €{sale:.2f}")
print(f"final price: €{final:.2f}")
print(f"overall : {change:+.2f}%")sale price : €80.00
final price: €80.00
overall : +0.00%
Expected output when solved:
sale price : €60.00
final price: €75.00
overall : -6.25%Hint: 25% off means multiplying by 0.75 and 25% on means multiplying by 1.25. Percent change is .
Solution
The two changes multiply: , which is a 6.25% drop. The 25% rise is taken of a smaller base.
original = 80.0
sale = original * (1 - 0.25)
final = sale * (1 + 0.25)
change = (final - original) / original * 100
print(f"sale price : €{sale:.2f}")
print(f"final price: €{final:.2f}")
print(f"overall : {change:+.2f}%")sale price : €60.00
final price: €75.00
overall : -6.25%
Exercise 4: Savings plan
€2 000 is invested at 4% per year, compounded once a year. Print the balance at the end of years 1, 2, 5 and 10. Then find the first whole year in which the balance has at least doubled.
principal, rate = 2000, 0.04
def balance(years):
# TODO: compound interest formula
return principal
for y in [1, 2, 5, 10]:
print(f"year {y:>2}: €{balance(y):,.2f}")
year = 0
# TODO: increase year until balance(year) >= 2 * principal
print("doubled after", year, "years")year 1: €2,000.00
year 2: €2,000.00
year 5: €2,000.00
year 10: €2,000.00
doubled after 0 years
Expected output when solved:
year 1: €2,080.00
year 2: €2,163.20
year 5: €2,433.31
year 10: €2,960.49
doubled after 18 yearsHint: . The "rule of 72" estimates the doubling time as years.
Solution
principal, rate = 2000, 0.04
def balance(years):
return principal * (1 + rate) ** years
for y in [1, 2, 5, 10]:
print(f"year {y:>2}: €{balance(y):,.2f}")
year = 0
while balance(year) < 2 * principal:
year += 1
print("doubled after", year, "years")year 1: €2,080.00
year 2: €2,163.20
year 5: €2,433.31
year 10: €2,960.49
doubled after 18 years
Exercise 5: Scientific notation
Write sci(x) that returns a number in scientific notation with three significant figures, like 3.00 × 10^8, by finding the exponent yourself with math.floor(math.log10(...)). Then compute the distance light travels in one year ().
import math
def sci(x):
# TODO: exponent = floor(log10(|x|)), mantissa = x / 10**exponent
return str(x)
for x in [299_792_458, 0.000_456, 6.02e23, -1234.5]:
print(sci(x))
print("light-year:", sci(299_792_458 * 31_557_600), "m")299792458
0.000456
6.02e+23
-1234.5
light-year: 9460730472580800 m
Expected output when solved:
3.00 × 10^8
4.56 × 10^-4
6.02 × 10^23
-1.23 × 10^3
light-year: 9.46 × 10^15 mHint: For 0.000456, is about −3.34, and the floor is −4, which is the exponent you want.
Solution
import math
def sci(x):
exponent = math.floor(math.log10(abs(x)))
mantissa = x / 10**exponent
return f"{mantissa:.2f} × 10^{exponent}"
for x in [299_792_458, 0.000_456, 6.02e23, -1234.5]:
print(sci(x))
print("light-year:", sci(299_792_458 * 31_557_600), "m")3.00 × 10^8
4.56 × 10^-4
6.02 × 10^23
-1.23 × 10^3
light-year: 9.46 × 10^15 m
A mantissa such as 9.996 would round to "10.00", so a production version also has to handle that edge case.
Exercise 6: How many digits?
A positive whole number has decimal digits and binary digits. Use this to fill in the table, and compare with len(str(n)) and n.bit_length().
import math
for n in [7, 100, 999, 1024, 2**40, 3**50]:
dec = 0 # TODO: digits from log10
bits = 0 # TODO: bits from log2
print(f"{dec:>3} {len(str(n)):>3} | {bits:>3} {n.bit_length():>3}") 0 1 | 0 3
0 3 | 0 7
0 3 | 0 10
0 4 | 0 11
0 13 | 0 41
0 24 | 0 80
Expected output when solved:
1 1 | 3 3
3 3 | 7 7
3 3 | 10 10
4 4 | 11 11
13 13 | 41 41
24 24 | 80 80Hint:
math.log10andmath.log2accept integers of any size. Usemath.floor(...) + 1.
Solution
import math
for n in [7, 100, 999, 1024, 2**40, 3**50]:
dec = math.floor(math.log10(n)) + 1
bits = math.floor(math.log2(n)) + 1
print(f"{dec:>3} {len(str(n)):>3} | {bits:>3} {n.bit_length():>3}") 1 1 | 3 3
3 3 | 7 7
3 3 | 10 10
4 4 | 11 11
13 13 | 41 41
24 24 | 80 80
For values just below a power of ten (like ) the float logarithm can round up to an exact integer and give one digit too many. len(str(n)) and bit_length() are exact.
Exercise 7: Simplify a square root
Write simplify_sqrt(n) that returns (a, b) with and as small as possible ( has no square factor). For example .
def simplify_sqrt(n):
a, b = 1, n
# TODO: for each k = 2, 3, ..., while k*k divides b, move a factor k out
return (a, b)
for n in [72, 50, 49, 180, 17, 1000]:
a, b = simplify_sqrt(n)
print(f"√{n} = {a}√{b}")√72 = 1√72
√50 = 1√50
√49 = 1√49
√180 = 1√180
√17 = 1√17
√1000 = 1√1000
Expected output when solved:
√72 = 6√2
√50 = 5√2
√49 = 7√1
√180 = 6√5
√17 = 1√17
√1000 = 10√10Hint: Each time
b % (k*k) == 0, doa *= kandb //= k*k, and test the same k again before moving on.
Solution
def simplify_sqrt(n):
a, b = 1, n
k = 2
while k * k <= b:
while b % (k * k) == 0:
a *= k
b //= k * k
k += 1
return (a, b)
for n in [72, 50, 49, 180, 17, 1000]:
a, b = simplify_sqrt(n)
print(f"√{n} = {a}√{b}")√72 = 6√2
√50 = 5√2
√49 = 7√1
√180 = 6√5
√17 = 1√17
√1000 = 10√10
Exercise 8: Class statistics
Compute the mean, median, mode, range and population standard deviation of the test scores without the statistics module, then compare with it.
import statistics
scores = [72, 85, 90, 66, 85, 78, 94, 85, 70, 75]
mean = 0 # TODO
median = 0 # TODO: sort, average the two middle values (even count)
mode = 0 # TODO: the most frequent value
rng = 0 # TODO: max - min
sd = 0 # TODO: sqrt of the average squared deviation
print(f"mine : mean={mean} median={median} mode={mode} range={rng} sd={sd:.3f}")
print(f"stats: mean={statistics.mean(scores)} median={statistics.median(scores)} "
f"mode={statistics.mode(scores)} sd={statistics.pstdev(scores):.3f}")mine : mean=0 median=0 mode=0 range=0 sd=0.000
stats: mean=80 median=81.5 mode=85 sd=8.718
Expected output when solved:
mine : mean=80.0 median=81.5 mode=85 range=28 sd=8.718
stats: mean=80 median=81.5 mode=85 sd=8.718Hint: For the mode, count with a dictionary or
list.countand take the value with the largest count.
Solution
import math
import statistics
scores = [72, 85, 90, 66, 85, 78, 94, 85, 70, 75]
n = len(scores)
mean = sum(scores) / n
s = sorted(scores)
median = (s[n // 2 - 1] + s[n // 2]) / 2
mode = max(set(scores), key=scores.count)
rng = max(scores) - min(scores)
sd = math.sqrt(sum((x - mean) ** 2 for x in scores) / n)
print(f"mine : mean={mean} median={median} mode={mode} range={rng} sd={sd:.3f}")
print(f"stats: mean={statistics.mean(scores)} median={statistics.median(scores)} "
f"mode={statistics.mode(scores)} sd={statistics.pstdev(scores):.3f}")mine : mean=80.0 median=81.5 mode=85 range=28 sd=8.718
stats: mean=80 median=81.5 mode=85 sd=8.718
statistics.mean prints 80 rather than 80.0 because it keeps the type of exact integer data when the mean is a whole number.
Exercise 9: Binary by hand
Implement to_binary(n) with repeated division by 2 (no bin() or format()), and from_binary(s) by adding place values (no int(s, 2)).
def to_binary(n):
# TODO: collect remainders of n // 2 steps, newest digit on the left
return "?"
def from_binary(s):
# TODO: value = value * 2 + digit, for each digit left to right
return 0
for n in [0, 6, 45, 255, 1000]:
b = to_binary(n)
print(f"{n:>4} -> {b:>10} -> {from_binary(b):>4} check {bin(n)}") 0 -> ? -> 0 check 0b0
6 -> ? -> 0 check 0b110
45 -> ? -> 0 check 0b101101
255 -> ? -> 0 check 0b11111111
1000 -> ? -> 0 check 0b1111101000
Expected output when solved:
0 -> 0 -> 0 check 0b0
6 -> 110 -> 6 check 0b110
45 -> 101101 -> 45 check 0b101101
255 -> 11111111 -> 255 check 0b11111111
1000 -> 1111101000 -> 1000 check 0b1111101000Hint: Handle separately, since the division loop never runs for it. Reading left to right, each new digit doubles everything seen so far.
Solution
def to_binary(n):
if n == 0:
return "0"
digits = ""
while n > 0:
n, r = divmod(n, 2)
digits = str(r) + digits
return digits
def from_binary(s):
value = 0
for ch in s:
value = value * 2 + int(ch)
return value
for n in [0, 6, 45, 255, 1000]:
b = to_binary(n)
print(f"{n:>4} -> {b:>10} -> {from_binary(b):>4} check {bin(n)}") 0 -> 0 -> 0 check 0b0
6 -> 110 -> 6 check 0b110
45 -> 101101 -> 45 check 0b101101
255 -> 11111111 -> 255 check 0b11111111
1000 -> 1111101000 -> 1000 check 0b1111101000
Exercise 10: Solve exactly
Write solve(a, b, c) that solves with exact Fraction arithmetic. It should return "no solution" or "every x" when . The inputs may be fractions given as strings such as "3/4".
from fractions import Fraction as F
def solve(a, b, c):
a, b, c = F(a), F(b), F(c)
# TODO: handle a == 0, otherwise x = (c - b) / a
return None
for eq in [("3", "1", "8"), ("3/4", "-2", "1/2"), ("-5", "7", "-8"), ("0", "2", "5"), ("0", "4", "4")]:
print(f"{eq[0]}x + ({eq[1]}) = {eq[2]} -> x = {solve(*eq)}")3x + (1) = 8 -> x = None
3/4x + (-2) = 1/2 -> x = None
-5x + (7) = -8 -> x = None
0x + (2) = 5 -> x = None
0x + (4) = 4 -> x = None
Expected output when solved:
3x + (1) = 8 -> x = 7/3
3/4x + (-2) = 1/2 -> x = 10/3
-5x + (7) = -8 -> x = 3
0x + (2) = 5 -> x = no solution
0x + (4) = 4 -> x = every xHint: With the equation reads , which is either always true or never true.
Solution
from fractions import Fraction as F
def solve(a, b, c):
a, b, c = F(a), F(b), F(c)
if a == 0:
return "every x" if b == c else "no solution"
return (c - b) / a
for eq in [("3", "1", "8"), ("3/4", "-2", "1/2"), ("-5", "7", "-8"), ("0", "2", "5"), ("0", "4", "4")]:
print(f"{eq[0]}x + ({eq[1]}) = {eq[2]} -> x = {solve(*eq)}")3x + (1) = 8 -> x = 7/3
3/4x + (-2) = 1/2 -> x = 10/3
-5x + (7) = -8 -> x = 3
0x + (2) = 5 -> x = no solution
0x + (4) = 4 -> x = every x
Test yourself
A price drops 20% and then rises 20%. Compared with the start it is:
- The same
- 4% higher
- 4% lower
- 20% lower
How many binary digits does 1000 have?
- 4
- 10
- 11
- 1000
What is in simplest radical form?