Exercise: Hillcrest 5K Results

Write six functions for a fun run's messy registrations and results, tidying names, standardizing t-shirt sizes, splitting names, counting sign-ups by weekday, and turning typed finish times into minutes and a pace per mile, and let pytest check what each one returns.

Apprentice · Python · Updated

By

The Hillcrest 5K Fun Run is over, and the race director needs three things from its files: a t-shirt order for next year, the day of the week to advertise on, and a results board with every runner's pace. The runners typed their own registrations and the timing volunteers typed the results, so names arrive as ' maria LOPEZ ', sizes as small, Med and X-Large, and finish times as 0:27:15 or 27:15. You'll write the six functions that tidy and measure them, and tests call each function and check what it hands back. A notebook comes with the exercise for looking at the data while you work.

Get the exercise code

Open this lesson's GitHub repository, github.com/ask-codey/exercise-data-5k-results, also linked from the Exercise box beside the lesson. Clone it into your python-course folder. In VS Code's terminal:

cd ~/python-course
git clone https://github.com/ask-codey/exercise-data-5k-results.git

Git makes a folder, exercise-data-5k-results, with the exercise code inside. Get the Exercise Code with Git walks through cloning step by step, if you'd like a reminder. Open that folder in VS Code (File > Open Folder), open its terminal with Terminal > New Terminal, and make the exercise's virtual environment. On Windows (PowerShell):

python -m venv .venv
.venv\Scripts\Activate.ps1
pip install -r requirements.txt

On a Mac (zsh):

python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt

The prompt starts with (.venv) once the virtual environment is on. The exercise's README says what each command does, and what to do if PowerShell won't run the second one. Then make the data, once:

python seed.py
Wrote registrations.csv: 450 rows.
Wrote results.csv: 432 rows.

The folder holds:

  • seed.py: makes registrations.csv (the 450 runners who signed up) and results.csv (the 432 who finished, in finishing order), our own made-up data. Its fixed random seed means everyone gets the same rows.
  • race.py: the six functions, for you to finish.
  • explore.ipynb: a notebook for looking at both files and trying your code. Choose the .venv kernel with Select Kernel (top right) before you run it. The tests don't read it.
  • report.py: tidies both files with your six functions and prints what they found. Ready to use.
  • tests/: the tests, which call each function and check what comes back, and conftest.py, which gives every test its own fresh copy of the files. You don't need to change them.
  • requirements.txt and pytest.ini: the packages the exercise needs, at exact versions, and where pytest finds the tests and your code.

What to do

Every function in race.py is already declared with its name and parameter, and for now it stops with a NotImplementedError that says Not built yet. The docstring under each one says what it should do, with examples:

def finish_minutes(results):
    """Return a new DataFrame with one more column, finish_minutes: each finish time in minutes.

    finish_time holds text the timing volunteers typed as hours:minutes:seconds, such as
    '0:27:15', or, for some runners under an hour, as minutes:seconds, such as '27:15'. Both
    mean 27 minutes 15 seconds. finish_minutes is a number rounded to 2 decimal places.

    '0:27:15' -> 27.25
    '27:15' -> 27.25
    '1:05:42' -> 65.7
    """
    raise NotImplementedError("Not built yet.")

In each function, replace the raise NotImplementedError("Not built yet.") line with your own code:

  1. tidy_names(df) returns a new table whose runner_name has no spaces at either end and is in title case: ' maria LOPEZ ' becomes Maria Lopez.
  2. standard_shirt_sizes(df) returns a new table whose tshirt_size holds only S, M, L or XL, whatever spelling and capitals the runner typed: small becomes S, Med becomes M, Lg becomes L and X-Large becomes XL. A spelling it can't place, such as XXL, stops it with a ValueError whose message names that spelling.
  3. split_names(df) returns a new table with two more columns, first_name and last_name, splitting each tidy runner_name at its first space only: Hugo Torres Vega becomes Hugo and Torres Vega.
  4. registrations_by_weekday(df) returns a Series counting the registrations on each day of the week, from the registered_at text such as 2026-09-02 18:45. Its index is Monday to Sunday in that order, with 0 for a day nobody registered on. Sign-ups on Tuesday, September 1, Tuesday, September 15 and Saturday, September 5 give Monday 0, Tuesday 2, Wednesday 0, Thursday 0, Friday 0, Saturday 1 and Sunday 0.
  5. finish_minutes(results) returns a new table with one more column, finish_minutes: each finish time in minutes, rounded to 2 decimal places. 0:27:15 and 27:15 both become 27.25.
  6. pace_per_mile(results) returns a new table with one more column, pace: the finish time divided by 3.1 miles, rounded to the nearest second and written as minutes:seconds with two digits for the seconds. 0:27:15 gives 8:47, and 0:18:36 gives 6:00.

Every function except registrations_by_weekday returns a new table and leaves the one it was given unchanged; the tests check that too. When a function changes or adds a column, start it with result = df.copy() (or results.copy()), change result, and return it.

Check your work

Run the tests from the exercise folder, with the virtual environment on:

python -m pytest

At first all 19 tests fail. That's expected: each function you finish turns its tests green. A failing test's message says what it called, what it expected and what came back, for example tidy_names(df)['runner_name'] for ' maria LOPEZ ', 'isaac SILVA', 'Nora Foster' should give ['Maria Lopez', 'Isaac Silva', 'Nora Foster'], but it gave [' maria LOPEZ ', 'isaac SILVA', 'Nora Foster'].

To see your functions at work on both files, run python report.py.

Hints

  • Look before you write. Run the notebook's cells: value_counts() shows every shirt spelling, and str.len().value_counts() shows the two ways the finish times were typed.
  • Tidy, then look up. Tidying Text with .str chains .str.strip() and .str.title(); lowercasing the sizes first means your dictionary needs one entry for Small, small and SMALL.
  • Let map tell you what it missed. Making Categories Match: replace and map counts the sizes that came out missing after map; any one of them is a spelling to name in the ValueError.
  • Split once. Splitting and Extracting Text shows n=1 and expand=True, and how to assign two columns at once.
  • Parse, then take the part. Parsing Dates with to_datetime reads registered_at with format="%Y-%m-%d %H:%M", and Parts of a Date: .dt counts by day_name() and puts the days in order with reindex. race.py already has the list of days, WEEK.
  • Fix the short times, don't drop them. Durations: Finish Times with Timedelta puts 0: in front of the 5-character times with mask, then uses .dt.total_seconds() and //, % and .str.zfill(2) for the pace.

When you're done

Every test is green: pytest's last line says 19 passed. And python report.py prints:

1) runners registered: 450
2) runners named Maria Lopez: 1
3) t-shirts to order: S 64, M 161, L 153, XL 72
4) runners with a two-word last name: 4
5) busiest day to register: Tuesday 141
6) finishers: 432
7) average finish (minutes): 34.6
8) the winner's pace per mile: 5:39
9) Maria Lopez's pace per mile: 5:54

Now look at lines 1 and 6: 450 runners registered and 432 finished. The other 18 bibs are in registrations.csv but not in results.csv: they signed up and never crossed the finish line. Does next year's t-shirt order on line 3 still need a shirt for every registration, and what would you tell the race director?

Submit your exercise

The exercise is how you finish this lesson. When your work is done, put it on GitHub in a repo of your own, then submit that repo's address here. Hand In Your Work with Git walks through each step.

  1. On GitHub, click +, then New repository. Name it (for example exercise-data-5k-results), choose Public, and click Create repository. Leave out the README: your folder already has one.

  2. In VS Code's terminal, in your exercise folder, send your work to your new repo. Point your copy at your own repo, then commit and push:

    git remote set-url origin https://github.com/your-name/exercise-data-5k-results.git
    git add .
    git commit -m "My solution"
    git push -u origin main
    
  3. Paste your repo's address, such as https://github.com/your-name/exercise-data-5k-results, into Submit your exercise on this page. The site checks that the repo is public and holds your commits, and then the lesson is complete.

Changed something after you submitted? Push it, and submit again: your latest submission is the one that counts.

So what

Text and dates are where typed data is messiest, and each fix here is a small, testable decision: what counts as the same name, which spelling means which size, where a name splits, which day a timestamp falls on, and what 27:15 really means. Written down as functions, next year's race gets the same careful answers.

Key terms

Related