Statistics Exercises
Time to practise! Each exercise has a starter playground that runs as-is and prints placeholder results in the expected format. Replace the TODO parts, press ▶ Run, and compare your output with the "Expected" lines. If you get stuck, open the solution, but give it a real try first.
| # | Exercise | Topics |
|---|---|---|
| 1 | Lunch vote | frequency tables, relative frequency, mode |
| 2 | Sleep diary | mean, median, standard deviation, range |
| 3 | Price outliers | quartiles, IQR, 1.5 × IQR rule |
| 4 | Commute probabilities | normal distribution |
| 5 | Average tip | confidence interval for a mean |
| 6 | Newsletter sign-ups | right-tailed proportion test |
| 7 | Faster checkout | two-sample t-test (left-tailed) |
| 8 | Ads and sales | correlation and linear regression |
| 9 | Fitness classes | chi-square test of independence |
1. Lunch vote
A team voted on where to order lunch. Print each option with its count and relative frequency (one decimal place, as a percentage), most popular first.
Expected first line: pizza 6 37.5%.
from collections import Counter
votes = ["pizza", "sushi", "pizza", "tacos", "curry", "pizza", "sushi", "tacos",
"pizza", "curry", "sushi", "pizza", "tacos", "sushi", "pizza", "curry"]
n = len(votes)
# TODO: count the votes and loop over them, most common first
for food, f in [("pizza", 0)]:
print(f"{food:6s} {f:2d} {0:.1%}")pizza 0 0.0%
Show solution
from collections import Counter
votes = ["pizza", "sushi", "pizza", "tacos", "curry", "pizza", "sushi", "tacos",
"pizza", "curry", "sushi", "pizza", "tacos", "sushi", "pizza", "curry"]
n = len(votes)
for food, f in Counter(votes).most_common():
print(f"{food:6s} {f:2d} {f / n:.1%}")Output: pizza 37.5%, sushi 25.0%, tacos and curry 18.8% each. The mode is pizza.
2. Sleep diary
Twelve nights of sleep (hours) are recorded. Print the sample mean, median, sample standard deviation and range, each with 2 decimals.
Expected: mean = 6.92, median = 6.90, stdev = 1.16, range = 4.20.
import statistics
sleep = [7.5, 6.0, 8.2, 5.5, 7.0, 6.8, 9.1, 6.5, 7.2, 4.9, 7.8, 6.6]
mean = 0.0 # TODO
median = 0.0 # TODO
stdev = 0.0 # TODO (sample standard deviation)
spread = 0.0 # TODO (range)
print(f"mean = {mean:.2f}")
print(f"median = {median:.2f}")
print(f"stdev = {stdev:.2f}")
print(f"range = {spread:.2f}")mean = 0.00
median = 0.00
stdev = 0.00
range = 0.00
Show solution
import statistics
sleep = [7.5, 6.0, 8.2, 5.5, 7.0, 6.8, 9.1, 6.5, 7.2, 4.9, 7.8, 6.6]
print(f"mean = {statistics.mean(sleep):.2f}")
print(f"median = {statistics.median(sleep):.2f}")
print(f"stdev = {statistics.stdev(sleep):.2f}")
print(f"range = {max(sleep) - min(sleep):.2f}")3. Price outliers
A comparison site lists the price of the same notebook in 12 shops. Use NumPy's default percentiles to find Q1, Q3 and the IQR, then flag outliers with the 1.5 × IQR rule.
Expected: Q1 = 13.75, Q3 = 16.25, IQR = 2.5, fences = [10.0, 20.0], outliers: [45, 2].
import numpy as np
prices = np.array([12, 15, 14, 18, 13, 16, 45, 14, 17, 15, 2, 16])
q1, q3 = 0.0, 0.0 # TODO: np.percentile
iqr = q3 - q1
low, high = 0.0, 0.0 # TODO: the fences
print(f"Q1 = {q1}, Q3 = {q3}, IQR = {iqr}")
print(f"fences = [{low}, {high}]")
print("outliers:", []) # TODO: select the prices outside the fencesQ1 = 0.0, Q3 = 0.0, IQR = 0.0
fences = [0.0, 0.0]
outliers: []
Show solution
import numpy as np
prices = np.array([12, 15, 14, 18, 13, 16, 45, 14, 17, 15, 2, 16])
q1, q3 = np.percentile(prices, [25, 75])
iqr = q3 - q1
low, high = q1 - 1.5 * iqr, q3 + 1.5 * iqr
print(f"Q1 = {q1}, Q3 = {q3}, IQR = {iqr}")
print(f"fences = [{low}, {high}]")
print("outliers:", prices[(prices < low) | (prices > high)].tolist())The 45 might be a typo or a luxury edition; the 2 might be a used copy. Check before removing either.
4. Commute probabilities
A bus ride takes on average 9.2 minutes with a standard deviation of 1.4 minutes, and ride times are approximately normal. Compute P(ride < 7 minutes), P(8 < ride < 11), and the time that only the slowest 5% of rides exceed.
Expected: 0.0580, 0.7050, 11.50.
from scipy import stats
mu, sigma = 9.2, 1.4
p_short = 0.0 # TODO: stats.norm.cdf
p_mid = 0.0 # TODO
slow = 0.0 # TODO: stats.norm.ppf
print(f"P(X < 7) = {p_short:.4f}")
print(f"P(8 < X < 11) = {p_mid:.4f}")
print(f"slowest 5% above {slow:.2f} minutes")P(X < 7) = 0.0000
P(8 < X < 11) = 0.0000
slowest 5% above 0.00 minutes
Show solution
from scipy import stats
mu, sigma = 9.2, 1.4
print(f"P(X < 7) = {stats.norm.cdf(7, mu, sigma):.4f}")
print(f"P(8 < X < 11) = {stats.norm.cdf(11, mu, sigma) - stats.norm.cdf(8, mu, sigma):.4f}")
print(f"slowest 5% above {stats.norm.ppf(0.95, mu, sigma):.2f} minutes")5. Average tip
A waiter recorded 14 tips (euros). Build a 95% t confidence interval for the mean tip.
Expected: mean = 4.143, 95% CI = (3.339, 4.947).
import numpy as np
from scipy import stats
tips = np.array([3.5, 5.0, 2.0, 4.5, 6.0, 3.0, 4.0, 5.5, 2.5, 4.0, 3.5, 7.0, 4.5, 3.0])
lo, hi = 0.0, 0.0 # TODO: stats.t.interval with stats.sem
print(f"mean = {tips.mean():.3f}, 95% CI = ({lo:.3f}, {hi:.3f})")mean = 4.143, 95% CI = (0.000, 0.000)
Show solution
import numpy as np
from scipy import stats
tips = np.array([3.5, 5.0, 2.0, 4.5, 6.0, 3.0, 4.0, 5.5, 2.5, 4.0, 3.5, 7.0, 4.5, 3.0])
lo, hi = stats.t.interval(0.95, len(tips) - 1, loc=tips.mean(), scale=stats.sem(tips))
print(f"mean = {tips.mean():.3f}, 95% CI = ({lo:.3f}, {hi:.3f})")6. Newsletter sign-ups
Historically, 30% of visitors to a blog sign up for the newsletter. After moving the sign-up box, 57 of 150 random visitors signed up. Test H₀: p = 0.30 against H₁: p > 0.30 at α = 0.05 with the one-proportion z-test.
Expected: p-hat = 0.380, z = 2.138, p-value = 0.0163 and reject H0.
import math
from scipy import stats
x, n, p0 = 57, 150, 0.30
p_hat = x / n
z = 0.0 # TODO: (p_hat - p0) / standard error under H0
p_value = 1.0 # TODO: right tail
print(f"p-hat = {p_hat:.3f}, z = {z:.3f}, p-value = {p_value:.4f}")
print("reject H0" if p_value <= 0.05 else "fail to reject H0")p-hat = 0.380, z = 0.000, p-value = 1.0000
fail to reject H0
Show solution
import math
from scipy import stats
x, n, p0 = 57, 150, 0.30
p_hat = x / n
z = (p_hat - p0) / math.sqrt(p0 * (1 - p0) / n)
p_value = stats.norm.sf(z)
print(f"p-hat = {p_hat:.3f}, z = {z:.3f}, p-value = {p_value:.4f}")
print("reject H0" if p_value <= 0.05 else "fail to reject H0")Conclusion: at the 5% level there is evidence that the sign-up rate is now above 30%. (This is an observational before/after comparison, so other changes over time could also explain it.)
7. Faster checkout
A shop tests a new checkout layout. Checkout times (seconds) were measured for 10 customers with the old layout and 10 different customers with the new one. Use a Welch t-test to check whether the new layout is faster (H₁: μ_new < μ_old).
Expected: means: old = 43.2, new = 37.5 and t = -3.678, p-value = 0.0009.
import numpy as np
from scipy import stats
old = np.array([42, 38, 45, 50, 41, 39, 47, 44, 40, 46])
new = np.array([37, 35, 41, 39, 36, 40, 34, 38, 42, 33])
t, p = 0.0, 1.0 # TODO: stats.ttest_ind(new, old, equal_var=False, alternative=...)
print(f"means: old = {old.mean():.1f}, new = {new.mean():.1f}")
print(f"t = {t:.3f}, p-value = {p:.4f}")means: old = 43.2, new = 37.5
t = 0.000, p-value = 1.0000
Show solution
import numpy as np
from scipy import stats
old = np.array([42, 38, 45, 50, 41, 39, 47, 44, 40, 46])
new = np.array([37, 35, 41, 39, 36, 40, 34, 38, 42, 33])
res = stats.ttest_ind(new, old, equal_var=False, alternative="less")
print(f"means: old = {old.mean():.1f}, new = {new.mean():.1f}")
print(f"t = {res.statistic:.3f}, p-value = {res.pvalue:.4f}")The order of the arguments matters: with new first, "less" means μ_new < μ_old.
8. Ads and sales
A small shop recorded its weekly advertising budget (thousand euros) and sales (thousand euros) for 8 weeks. Compute Pearson's r, fit a regression line and predict sales for a budget of 4.0.
Expected: r = 0.997, sales = 7.44 + 5.680 × ads, prediction for 4.0: 30.2.
from scipy import stats
ads = [1.2, 2.0, 2.5, 3.1, 3.8, 4.4, 5.0, 5.9]
sales = [14, 19, 22, 24, 30, 33, 35, 41]
r, b0, b1 = 0.0, 0.0, 0.0 # TODO: use stats.linregress
print(f"r = {r:.3f}")
print(f"sales = {b0:.2f} + {b1:.3f} × ads")
print(f"prediction for 4.0: {b0 + b1 * 4.0:.1f}")r = 0.000
sales = 0.00 + 0.000 × ads
prediction for 4.0: 0.0
Show solution
from scipy import stats
ads = [1.2, 2.0, 2.5, 3.1, 3.8, 4.4, 5.0, 5.9]
sales = [14, 19, 22, 24, 30, 33, 35, 41]
res = stats.linregress(ads, sales)
print(f"r = {res.rvalue:.3f}")
print(f"sales = {res.intercept:.2f} + {res.slope:.3f} × ads")
print(f"prediction for 4.0: {res.intercept + res.slope * 4.0:.1f}")Each extra thousand euros of advertising goes with about 5.7 thousand euros more sales, but this is observational data: busy seasons might drive both budget and sales.
9. Fitness classes
A gym asked 200 members which class they prefer. Is preference independent of membership type? Rows: basic, premium; columns: yoga, spinning, strength.
Expected: chi2 = 7.467, df = 2, p-value = 0.0239.
from scipy import stats
table = [[48, 22, 30], # basic
[32, 38, 30]] # premium
chi2, df, p = 0.0, 0, 1.0 # TODO: stats.chi2_contingency
print(f"chi2 = {chi2:.3f}, df = {df}, p-value = {p:.4f}")chi2 = 0.000, df = 0, p-value = 1.0000
Show solution
from scipy import stats
table = [[48, 22, 30], [32, 38, 30]]
res = stats.chi2_contingency(table)
print(f"chi2 = {res.statistic:.3f}, df = {res.dof}, p-value = {res.pvalue:.4f}")At α = 0.05 we reject independence: basic members lean towards yoga, premium members towards spinning.
Test yourself
In exercise 7, why is alternative="less" correct when calling ttest_ind(new, old, ...)?
- Because the new times are smaller numbers
- Because H₁ says the mean of the first argument (new) is less than the mean of the second (old)
- Because left-tailed tests are the default
- It isn't; it should be two-sided
In exercise 3, why use the 1.5 × IQR rule rather than mean ± 2 standard deviations to find outliers?
- It is faster to compute
- The outliers themselves inflate the mean and SD, hiding outliers; quartiles are robust
- Standard deviations can't be computed for prices
- There is no difference