Get started ยท Choose a problem ยท How to ยท Notebooks ยท Further reading
Welcome! This is a collection of Python problems to solve. You solve them by writing functions that start as stubs and whose tests fail and are red. If you complete them correctly the tests will turn green!
Problems run from FizzBuzz-sized warm-ups to data analysis, simulation, algorithms and statistical modelling. Along the way you will meet list comprehensions, generators, recursion, object orientation, refactoring, graph search, maximum likelihood, expectation-maximisation, probabilities that defy intuition and even a cellular automaton.
The dev container is ready to use, but not required. For a local setup with the notebooks and scientific tools, install the complete environment with:
uv sync --all-groups --extra scienceThen try a first exercise, for example the quick warm-up Q1: Exponentiation:
-
Read the prompt, then run its test. It is expected to fail at first:
uv run pytest exercises/python_fundamentals/test_fundamentals.py -k exponentiate -q
-
Implement
exponentiateinexercises/python_fundamentals/fundamentals.py. -
Rerun the same command until it passes.
-
Keep going with the Python language problems, or pick any other!
New to VS Code, environments or reading test failures? Follow Getting going in VS Code for a step-by-step walkthrough, including how to use the Testing panel and keep the output manageable.
For an overview of the repository layout and development setup, see DEVELOPMENT.md.
Pick a topic that interests you. Each link opens an exercise folder under
exercises/ that holds everything for that problem: its instructions (the
README), starter code, tests, and any notebook or data. The index groups
exercises by topic, and each is marked with its difficulty (๐ถ๏ธ gentle, ๐ถ๏ธ๐ถ๏ธ
takes some thought, ๐ถ๏ธ๐ถ๏ธ๐ถ๏ธ challenging).
If you are new to Python, start with the fundamentals. Otherwise, dip in wherever you like; the notes below flag useful background, not a required order. Not sure how to work through a problem, or what the ๐ก and ๐ markers mean? See How to work through the problems below.
If you would like a guided path, here are two suggested routes. Each starts with the fundamentals and builds on the one before:
- Python for experimental scientists: Python Fundamentals โ Steak, Tea, and Toast โ Penguin parade โ Spinning plates โ Titanic disaster.
- Programming and problem-solving: Python Fundamentals โ Wordsmith โ Word ladder โ Try, try again โ Sequence alignment.
Practise writing clear Python, organising it with classes, and improving it through tests and refactoring.
- Python Fundamentals ๐ถ๏ธ: short language exercises covering exponentiation, adjacent products, FizzBuzz, Fibonacci and look-and-say generators, the first non-repeating character, and Python gotchas.
- Noisy animals ๐ถ๏ธ๐ถ๏ธ: build a cast of talking animals, from noisy animals and a silent fox to a parrot that learns and a robot. Practise classes, inheritance and polymorphism.
- Gilded Rose ๐ถ๏ธ๐ถ๏ธ: tame an inherited codebase without breaking its existing behaviour. Familiarity with classes helps.
Solve puzzles that reward clever strategies over brute force. Discover how to explore large spaces of possibilities, avoid repeating work, and keep your code fast enough as the problems grow.
- Word ladder ๐ถ๏ธ๐ถ๏ธ: turn
playintogameone letter at a time. - Try, try again ๐ถ๏ธ๐ถ๏ธ: count the ways a rugby score could have happened, from recursion to dynamic programming. The Fibonacci exercise is useful background.
- Sudoku solver ๐ถ๏ธ๐ถ๏ธ๐ถ๏ธ: warm up with a checker, then backtrack your way to a solution.
- Sequence alignment ๐ถ๏ธ๐ถ๏ธ๐ถ๏ธ: align two DNA sequences and discover why brute force cannot scale. The rugby problem introduces the dynamic programming ideas used here.
Explore data, look for relationships, and evaluate predictions on unseen data. Learn to use pandas to hold, clean, join and summarise data in data frames. These notebook-based exercises use the optional scientific stack.
- Mysterious data ๐ถ๏ธ: thirteen datasets with matching summaries. What do their plots reveal?
- Penguin parade ๐ถ๏ธ: Reconcile real biological measurements in a dataset for penguins from the Palmer Archipelago in Antarctica, investigate missing lab results and see what blood isotopes reveal.
- Steak, Tea, and Toast ๐ถ๏ธ๐ถ๏ธ: clean messy responses and investigate associations between preferences from a real survey on facebook.
- Titanic disaster ๐ถ๏ธ๐ถ๏ธ: build a prediction pipeline, beat a baseline, and test it on unseen passengers from the Titanic disaster.
- Spinning plates ๐ถ๏ธ๐ถ๏ธ๐ถ๏ธ: rescue a seemingly failed laboratory experiment performed on a 96 well plate: parse plate-reader files, reconstruct the sample mapping, build a tidy DataFrame pipeline and decide whether the results can be trusted.
Use repeated experiments to find out how much you can trust an estimate. Basic NumPy, probability and statistics help.
- Known unknowns ๐ถ๏ธ๐ถ๏ธ: estimate uncertainty with standard errors, the bootstrap and confidence intervals, then use simulation to test whether each method keeps its promise.
- No median feat ๐ถ๏ธ๐ถ๏ธ: see how one wild value can wreck a mean, then build from the median to the MAD and TheilโSen regression, and use simulation to measure what that protection costs.
Estimate model parameters using likelihood, numerical optimisation and mixture models fitted by expectation-maximisation, or weigh evidence in real football data with Bayesian updating. Start with likelihood for coins, normals and straight lines; the mixture exercises build on it, with covariance matrices needed for multivariate mixtures.
- A likely story ๐ถ๏ธ๐ถ๏ธ: write down the probability of one data point and fit any model with it, from a coin to a robust regression.
- Golden Boot ๐ถ๏ธ: who is the best goalscorer in the Premier League? Use real 2017/18 data and Bayesian updating to see why a short record flatters a striker.
- Fitting a mixture ๐ถ๏ธ๐ถ๏ธ๐ถ๏ธ: write the mixture likelihood, then use hidden labels to fit hard and soft mixtures and a bivariate mixture to Old Faithful.
Probability puzzles where your gut is confidently wrong. Predict, simulate, calculate and explain, using only the Python standard library; the investigations use the science packages for plots.
- Office party ๐ถ๏ธ: how many people are required before a shared birthday is more likely than not?
- Waiting for heads ๐ถ๏ธ๐ถ๏ธ: why is
waiting for
HHdifferent from waiting forHT? - The 100 prisoners ๐ถ๏ธ๐ถ๏ธ๐ถ๏ธ: find a strategy for a hopeless-looking last chance at freedom.
Explore how simple rules produce complex behaviour: a breeding population, deterministic cellular automata and stochastic evolution. All three exercises use NumPy.
- Breed like rabbits ๐ถ๏ธ: simulate a population of rabbits as their breeding rate changes, and see what a one-line rule can do.
- Game of Life ๐ถ๏ธ๐ถ๏ธ: build a cellular automaton and watch patterns grow and move.
- Dawkins' weasel ๐ถ๏ธ๐ถ๏ธ: can a sentence evolve out of gibberish through mutation and selection? Optional extensions add a tournament-selection genetic algorithm, then recombination.
- Wordsmith ๐ถ๏ธ๐ถ๏ธ: train a tiny probabilistic language model on English words, invent new ones, and investigate whether remembering more characters makes a better wordsmith.
You do not need to do everything, or to do things in order. Problems range from a few minutes to several sessions.
- Each exercise's README, linked from the index, opens with anything you need beforehand and the test command that checks it. The same folder holds the starter code, the tests and any notebook or data. Some READMEs group several related exercises.
- Use the focused test command for the exercise you are working on. Most
exercises begin as stubs, so their tests are red until you implement them.
Run several exercises together by listing their folders, for example
uv run pytest exercises/word_ladder/ exercises/sudoku_solver/ -q; that is more useful after you have completed several exercises. - Aim to make one small change at a time and rerun the test.
- The early language exercises use only the Python standard library; scientific exercises need the optional science packages installed above.
Difficulty is a rough guide, shown at the top of each exercise README as well as in the index: ๐ถ๏ธ gentle, ๐ถ๏ธ๐ถ๏ธ takes some thought, ๐ถ๏ธ๐ถ๏ธ๐ถ๏ธ challenging. A page may start gently and build up.
When working through the problems, look out for these markers:
- ๐ก a hint (in a footnote or a collapsible section, sometimes in three levels that give away a little more each time)
- ๐ an optional extension.
Look for hints only when you are stuck, opening one level at a time, and try the extensions if you want more. Click a collapsible section's heading to open it. Some investigations also end with a collapsible What did you discover? section: read it after you have formed your own view.
Tip
Try each problem yourself first. Use coding agents for hints, explanations and reviews of your attempts.
Using coding agents while learning
The purpose of this package is partially to help you learn Python, but is also a collection of interesting and hopefully satisfying problems to solve. It is not simply about collecting completed solutions. A coding agent could complete the exercises for you, but that would miss the point entirely. Writing code, investigating failures, and explaining your choices build an understanding of Python, statistics and algorithms that remain useful in the age of agentic coding. You'll need this understanding to specify requirements, assess generated code, spot mistakes, and maintain the result. Consider using agents to support your learning with hints, explanations, or reviews of your own attempts. Try each problem yourself first, and make sure you can explain and test any code you adopt; passing tests alone is not the learning goal.
AGENTS.md gives compatible coding agents learning-first guidance: offer hints before solutions and ask before editing your exercise code. Support varies by tool; if yours does not load it automatically, ask it to read the guide first.
Each exercise's notebook (usually investigate.ipynb) sits in its exercise
folder next to the instructions. It is a workspace for your investigation,
not a completed example. Open it in VS Code with Jupyter support, or run
uv run jupyter lab from the repository root. Use the project's .venv as
the kernel, with the notebook and science packages installed as described above.
A few notebooks have a more specific name: old_faithful.ipynb applies the
mixture models to the Old Faithful geyser data (in
exercises/fitting_a_mixture/data/), simulation.ipynb checks statistical
methods against simulated data with known answers, and playground.ipynb is a
place to play with your finished code. Each problem has its own notebook, so you
only need the one in your exercise folder.
The Titanic notebook is a staged machine-learning investigation. Its setup reserves a test set: keep exploration and model selection on the training rows, then open the test set only for the final evaluation.
Run the setup cells first, then fill the TODO cells for your investigation,
running any earlier cells that section depends on. Implement reusable functions
in the source module named by the problem and check them with its tests; use
the notebook to call those functions, run experiments and make plots. Add code
cells as needed, and Markdown cells for your predictions, observations and
explanations. Use seeded random generators so experiments can be repeated.
Notebook investigations have no automatic pass or fail: your plots, numerical checks and explanations are the result.
Use these when you need background or want to go beyond an exercise; none is required reading before you start.
- The Python Tutorial explains core language features, including generators and classes. Use it alongside the Pythonic Python exercises when a concept is unfamiliar.
- Python Standard Library is the reference
for built-in tools. Look up
itertools,collectionsandrandomfor the language exercises and probability simulations. - pytest documentation explains assertions, parametrisation and fixtures. Use it to understand the supplied tests.
- NumPy quickstart introduces arrays, axes and broadcasting: useful foundations for the simulations, cellular automaton and mixture models.
- pandas getting started covers selecting, cleaning, grouping and plotting tabular data. These are the main tools used in the data-analysis notebooks.
- SciPy statistics tutorial explains probability distributions, sampling and distribution functions. Consult it for the uncertainty investigations and likelihood calculations.
- SciPy optimisation tutorial explains numerical minimisation and constraints. It provides background for fitting coins, normals, regressions and mixtures by maximising their log-likelihoods.
- scikit-learn getting started introduces fitting, prediction, preprocessing and pipelines. It is a useful companion to the Titanic exercise's unfamiliar library calls.
- scikit-learn cross-validation guide explains validation strategies and their relationship to a separate test set. Read it to understand or extend the Titanic evaluation workflow.
- Expectation-maximisation gives the broader latent-variable interpretation of EM. Read it after the mixture exercise to connect its alternating steps to the general method.
Videos and talks that inspired some of the exercises. They are good for
motivation, but
- Inventing Game of Life (John Conway) (Numberphile): Conway describes how he came to invent the automaton. For Game of Life.
- Titanic: Machine Learning from Disaster: the Kaggle competition Titanic disaster is modelled on.
โ ๏ธ The Feigenbaum Constant (4.669): contains a spoiler for Breed like rabbits.โ ๏ธ Python Sudoku Solver: contains a spolier for Sudoku solver.โ ๏ธ The unbelievable solution to the 100 prisoner puzzle contains a spoiler for The 100 prisoners.โ ๏ธ Penney's Game (Numberphile): contains a spoiler for the game extension of Waiting for heads.โ ๏ธ All the Little Things (Sandi Metz, RailsConf 2014): shows a possible solution for Gilded Rose.