Exercise: Pantry and Shopping List

Write the five functions behind a recipe app's pantry, with a dictionary of amounts, sets of ingredients, a set difference, comprehensions and sorting with a key, and let pytest's tests check each one.

Apprentice · Python · Updated

By

Pantry Pal, a recipe app, knows what's in your kitchen and what every recipe needs, and its buttons don't work yet. You'll write the five functions behind them: whether you have enough of something, what to buy for a recipe, which recipes you can make right now, what's left after you cook, and what you have the most of. The pantry is a dictionary of ingredients to amounts and each recipe's ingredients are a set, so every tool from this chapter has a job here.

Get the exercise code

Open this lesson's GitHub repository, github.com/ask-codey/exercise-python-pantry-shopping-list, 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-python-pantry-shopping-list.git

Git makes a folder, exercise-python-pantry-shopping-list, 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, the same three steps as in the exercises before. 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.

The folder holds:

  • pantry.py: the five functions, for you to finish.
  • kitchen.py: prints Pantry Pal's kitchen report with your functions, so you can see them at work. Ready to use.
  • tests/test_pantry.py: the tests, which call each function and check what comes back, or what the pantry holds afterward. You don't need to change it.
  • requirements.txt and pytest.ini: the package the tests need, and where pytest finds the tests and your code.

The tests and kitchen.py bring your functions in with an import line, such as from pantry import has_enough. import and the Standard Library explains how that works, in Module 3.

What to do

Every function in pantry.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:

def has_enough(pantry, ingredient, amount):
    """Return True when the pantry has at least amount of the ingredient, and False when it doesn't.

    pantry is a dictionary of each ingredient's name to the amount you have.
    Having exactly amount counts as enough. An ingredient the pantry doesn't
    list counts as 0.

    has_enough({"eggs": 6, "flour": 4}, "eggs", 2) -> True
    has_enough({"eggs": 6, "flour": 4}, "flour", 4) -> True    (exactly enough)
    has_enough({"eggs": 6, "flour": 4}, "milk", 1) -> False    (no milk at all)
    """
    raise NotImplementedError("Not built yet.")

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

  1. has_enough(pantry, ingredient, amount) returns True when the pantry has at least amount of the ingredient, and False when it doesn't. An ingredient the pantry doesn't list counts as 0.
  2. shopping_list(recipe, pantry) returns what to buy for a recipe, as a list sorted from A to Z. recipe is a set of the ingredients it needs, and you buy each one the pantry doesn't list, or lists with an amount of 0.
  3. recipes_you_can_make(recipes, pantry) returns the names of the recipes with nothing on their shopping list, in the same order as in recipes, a dictionary of each recipe's name to its set of ingredients.
  4. use_ingredients(pantry, used) takes what a recipe used out of the pantry. It's the one function that changes the pantry it's given, and it returns nothing. An amount never goes below 0, and an ingredient the pantry doesn't list is skipped.
  5. most_stocked(pantry, count=3) returns the names of the count ingredients you have the most of, the most first. Ingredients with the same amount keep the pantry's order.

Check your work

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

pytest

At first all 18 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 has_enough(pantry, "bread", 1) should return False, but it returned True. For use_ingredients, it says what the pantry should hold after the call, and what it holds.

To see your functions at work, run python kitchen.py. It prints the kitchen report from your five functions.

Hints

  • Work an example through by hand first. For the pancakes, the pantry has eggs, flour and butter, but the butter's amount is 0 and there's no milk at all: what's on the shopping list? The docstrings' examples are the tests' examples.
  • Missing counts as 0. .get() with a default reads an amount without stopping on a missing key, as Dictionaries: Looking Things Up by Name shows.
  • What's in stock is a set too. A set comprehension with an if can collect the ingredients you have more than 0 of, and then one operator from Sets: No Duplicates Allowed leaves what the recipe needs that isn't among them.
  • An empty list counts as false. if not shopping_list(...) is true when there's nothing to buy, which fits in a list comprehension's if.
  • Sort the pairs, then keep the names. Sorting with key and lambda sorts a dictionary's items by their values; a slice keeps the first few, and a comprehension takes each name.

When you're done

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

Pantry Pal: what's cooking
You can make: ['Pancakes', 'Sugar cookies']
For an omelet, buy: ['cheese']
For French toast, buy: ['bread']
Enough eggs for two batches of pancakes? True
Most stocked: ['eggs', 'flour', 'sugar']

After the pancakes: {'eggs': 4, 'flour': 2, 'milk': 1, 'butter': 0, 'sugar': 3, 'cheese': 0}
You can make: []

Now look back at recipes_you_can_make. Did it work out the shopping list again, or call shopping_list? If Pantry Pal changed its rule so that an amount under 1 counts as missing, how many of your functions would need the change?

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-python-pantry-shopping-list), 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-python-pantry-shopping-list.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-python-pantry-shopping-list, 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

Dictionaries for what you have, sets for what you need, and comprehensions and sorting to answer questions about both: that's the shape of most data work, from a recipe app's pantry to a store's stock.

Key terms

Related