Data Science Analysis Exercises
Practise validation and denominator choices before comparing kiosk rates.
How it works
This exercise combines two common analytical pitfalls: unequal exposure and invalid input. The task is to calculate a period rate from nonnegative litre totals and positive opening hours. Predict the result for days with ten litres in one hour and thirty litres in five hours. Then check that a missing or zero-hour day is rejected rather than given an invented denominator.
Run the code
Try in playground opens the correct numpy editor and preloads the complete source. Choose Run to execute; loading does not execute it. The isolated browser runtime does not read personal PC files.
Local review: Python 3.12.14, NumPy 2.5.4, Pandas 3.0.6 and SciPy 1.18.0. Browser review: Pyodide 0.27.7, Python 3.12.7, NumPy 2.0.2, Pandas 2.2.3 and SciPy 1.14.1 in their respective editors. Save the download as analysis-exercises.py and run python analysis-exercises.py in your separate environment. Apache and MySQL are not needed. Environment setup.
Example
import numpy as np
def period_rate(litres, hours):
litres, hours = np.asarray(litres, dtype=float), np.asarray(hours, dtype=float)
if litres.ndim != 1 or litres.size == 0 or litres.shape != hours.shape:
raise ValueError("matching nonempty vectors required")
if not np.isfinite(litres).all() or not np.isfinite(hours).all() or (litres < 0).any() or (hours <= 0).any():
raise ValueError("invalid measurement")
return litres.sum()/hours.sum()
rate = period_rate([10.,30.],[1.,5.])
assert np.isclose(rate, 40/6)
assert not np.isclose(rate, np.mean([10.,6.]))
try:
period_rate([10.],[0.])
except ValueError:
print(f"Period rate {rate:.3f} L/hour; zero-hour input rejected")
else:
raise AssertionError("invalid hours accepted")
Expected result
Period rate 6.667 L/hour; zero-hour input rejected
The answer uses forty litres divided by six hours, not the unweighted mean of daily rates. The function checks matching shapes and finite values before calculating. Its numeric conversion accepts convertible values, unlike the stricter measurement contract earlier; callers should validate a broader input schema before using it in a service.
Technical references: NumPy, Pandas and SciPy. For evaluation design see the scikit-learn guide to leakage; these examples do not require scikit-learn.