# Exercise: How Many Loaves?

Write four plain-Python functions that hold back Sunrise Bakery's last two weeks as test days, guess them with the average and with a weekday rule learned from the training days, and measure each guess's average miss, and let pytest check the split, the arithmetic and that no test day goes into a guess.

Apprentice · AI Basics · Python · Updated November 19, 2026

By Gregor Dzierzon

Sunrise Bakery's owner wants to know, honestly, whether the weekday averages are worth baking by. You'll write the four functions that answer it: one that holds the last two weeks back as test days, one for the baseline guess, one for the weekday rule, and one that measures how far off a set of guesses is. It's all plain Python, lists and dictionaries, with no machine learning library yet: the ideas come first. Tests call each function and check what it gives back.

## Get the exercise code

Open this lesson's GitHub repository, [github.com/ask-codey/exercise-ml-how-many-loaves](https://github.com/ask-codey/exercise-ml-how-many-loaves), also linked from the **Exercise** box beside the lesson. Clone it into your `python-course` folder. In VS Code's terminal:

```bash
cd ~/python-course
git clone https://github.com/ask-codey/exercise-ml-how-many-loaves.git
```

Git makes a folder, `exercise-ml-how-many-loaves`, with the exercise code inside. 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):

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

On a Mac (zsh):

```bash
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.

The folder holds:

- `bakery_days.csv`: the 120 days, our own made-up data, the same file the chapter's lessons use.
- `seed_data.py`: the script that made the CSV, with the pattern it planted. You don't need to run it: the committed CSV is what keeps everyone's numbers the same.
- `loaves.py`: the four functions, for you to finish, and `load_days`, which reads the CSV into a list of dictionaries, ready to use.
- `report.py`: holds back the last two weeks, guesses them both ways with your functions, and prints what each step gave. Ready to use.
- `tests/`: the tests, which call each function and check what comes back, and `conftest.py`, which gives each test a fresh copy of the 120 days. You don't need to change them.
- `requirements.txt` and `pytest.ini`: the packages the exercise needs, at exact versions (pytest, and NumPy for `seed_data.py` only), and where pytest finds the tests and your code.

## What to do

Every function in `loaves.py` is already declared with its name and parameters, 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. A day is a dictionary such as `{"day": 6, "weekday": "Saturday", "high_temp_f": 72, "is_holiday": 0, "loaves_sold": 143}`:

```python
def mean_miss(guesses, actual):
    """Return the average miss: for each day, the distance between its guess and what it
    really sold, as a positive number, averaged over the days. Not rounded.

    guesses and actual are lists of the same length, in the same order of days.

    mean_miss([100, 110], [90, 130]) -> 15.0   (misses of 10 and 20)
    mean_miss([140.0], [140])        -> 0.0
    """
    raise NotImplementedError("Not built yet.")
```

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

1. **`hold_out_last(days, n)`** returns two lists, `train, test`: the last `n` days as the test days, and every day before them as the training days, both still in time order. It doesn't change `days`. With the 120 days and `n` of 14: 106 training days (days 1 to 106) and 14 test days (days 107 to 120).
2. **`average_guess(train)`** returns the baseline: the average `loaves_sold` of the training days, not rounded. Days that sold 90, 96 and 84 loaves give `90.0`.
3. **`weekday_rule_guess(day, train)`** returns the average `loaves_sold` of the training days with the same `"weekday"` as `day`, not rounded: training Saturdays of 143, 139 and 138 loaves give `140.0` for a Saturday. It uses only `day["weekday"]`, never `day["loaves_sold"]`, which is the answer the guess is scored against. If no training day has that weekday, it returns `average_guess(train)`.
4. **`mean_miss(guesses, actual)`** returns the average miss: for each day, the distance between the guess and what it sold, as a positive number, averaged. Guesses of 100 and 110 against 90 and 130 sold give `15.0`.

The split comes first, and both guesses learn from the training days only: that's what keeps the test days ones the guesses never saw.

## Check your work

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

```bash
python -m pytest
```

At first all 15 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 *len(test) after hold_out_last(days, 14) should return 14, but it returned 106.* No test checks how good the guesses are: the tests check the split, the arithmetic, and that no test day ever goes into a guess.

To see your functions at work on the whole file, run `python report.py`.

## Hints

- **Look before you write.** Open `bakery_days.csv` in VS Code and read the last few rows: those are the days `hold_out_last` holds back.
- **Two slices.** Negative positions count from the end of a list, as *Training and Testing: Never Grade Your Own Homework* shows, so the last `n` items and the items before them are two slices. A slice is a new list, so `days` stays as it was.
- **An average is a total and a count.** Pick out the `loaves_sold` you need with a loop or a list comprehension, then divide the total by how many there are, as *The Simplest Guess: Baselines* does.
- **Only the same weekday.** In `weekday_rule_guess`, an `if` that compares each training day's `"weekday"` with `day["weekday"]` picks the days that count. Check for an empty list before you divide.
- **Pair them up.** `zip(guesses, actual)` gives each day's guess and real loaves together in a `for` loop, and `abs()` turns a difference into a positive miss.

## When you're done

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

```text
1) days: 120
2) training days: 106
3) test days: 14 (day 107 to day 120)
4) the average guess: 100.0
5) the average guess, average miss on the test days: 16.6
6) the weekday rule, guess for day 113 (a Monday): 93.6
7) the weekday rule, average miss on the test days: 6.9
```

The weekday rule's misses are well under half the baseline's: knowing the day of the week is worth something. Now look at day 113, a holiday Monday that sold 117 loaves. How far off was the weekday rule's guess, and which column in the file could help a better rule see that day coming?

## 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-ml-how-many-loaves`), 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:

   ```bash
   git remote set-url origin https://github.com/your-name/exercise-ml-how-many-loaves.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-ml-how-many-loaves`, 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

Hold the newest days back, make the simplest guess and a better one from the training days only, and score both on the days they never saw: that's the honest test every model in this course has to pass, written here in a few lines of plain Python.

## Key terms

- [Training Data](https://www.ask-codey.com/glossary/training-data)
- [Test Data](https://www.ask-codey.com/glossary/test-data)
- [Baseline](https://www.ask-codey.com/glossary/baseline-ai)
- [Mean Absolute Error](https://www.ask-codey.com/glossary/mean-absolute-error)
- [pytest](https://www.ask-codey.com/glossary/pytest)

## Related

- [Guessing from Examples](https://www.ask-codey.com/lessons/ml-guessing-from-examples)
- [Training and Testing: Never Grade Your Own Homework](https://www.ask-codey.com/lessons/ml-training-and-testing)
- [The Simplest Guess: Baselines](https://www.ask-codey.com/lessons/ml-baseline-guesses)

Source: https://www.ask-codey.com/lessons/exercise-ml-how-many-loaves
