Skip to content

About

Python exercises from FizzBuzz to mixture models: turn failing tests from red to green

Topics

Resources

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

ย 

History

104 Commits

Folders and files

Repository files navigation

Red to Green: Python problems from FizzBuzz to mixture models

Get started ยท Choose a problem ยท How to ยท Notebooks ยท Further reading

Introduction

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.

Getting started ๐Ÿšฆ

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 science

Then try a first exercise, for example the quick warm-up Q1: Exponentiation:

  1. 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
  2. Implement exponentiate in exercises/python_fundamentals/fundamentals.py.

  3. Rerun the same command until it passes.

  4. 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.

The problems ๐Ÿšจ

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:

Pythonic Python

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.

Algorithms and Search

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 play into game one 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.

Data Analysis

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.

Uncertainty and Simulation

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.

Parameter Estimation

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.

Against the Odds

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 HH different from waiting for HT?
  • The 100 prisoners ๐ŸŒถ๏ธ๐ŸŒถ๏ธ๐ŸŒถ๏ธ: find a strategy for a hopeless-looking last chance at freedom.

Models of Life

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.

Generative Models

  • Wordsmith ๐ŸŒถ๏ธ๐ŸŒถ๏ธ: train a tiny probabilistic language model on English words, invent new ones, and investigate whether remembering more characters makes a better wordsmith.

How to work through the problems ๐Ÿงญ

You do not need to do everything, or to do things in order. Problems range from a few minutes to several sessions.

The basic workflow

  • 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.

Hints, difficulty and extensions ๐Ÿ’ก

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.

Using coding agents ๐Ÿค–

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.

Working with notebooks ๐Ÿ““

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.

Further Reading ๐Ÿ“š

Use these when you need background or want to go beyond an exercise; none is required reading before you start.

Python and testing

  • 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, collections and random for the language exercises and probability simulations.
  • pytest documentation explains assertions, parametrisation and fixtures. Use it to understand the supplied tests.

Working with scientific data

  • 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.

Prediction and model fitting

  • 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.

Inspiration

Videos and talks that inspired some of the exercises. They are good for motivation, but โš ๏ธ marks those that give away ideas or solutions, so attempt the exercise first.

About

Python exercises from FizzBuzz to mixture models: turn failing tests from red to green

Topics

Resources

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages