Exercise: Outdoor Gear Finder

Write five functions for an outdoor gear store's online gear finder, filtering its catalog by budget and by stock, listing the best-rated products fairly, adding price bands with pd.cut and sale prices with np.where, and let pytest check the table each one returns.

Apprentice · Python · Updated

By

Trailhead Outfitters, an outdoor gear store, is adding a gear finder to its website. A shopper should be able to see what fits their budget, which stoves are in stock right now, the best-rated gear (without a 5.0 from two reviews taking first place), a price band on every product, and this weekend's sale prices. You'll write the five functions behind it, each one a question about the store's catalog, and tests call each function and check the table it hands back. A notebook comes with the exercise for looking at the catalog while you work.

Get the exercise code

Open this lesson's GitHub repository, github.com/ask-codey/exercise-data-gear-finder, 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-gear-finder.git

Git makes a folder, exercise-data-gear-finder, 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 products.csv: 300 rows.

The folder holds:

  • seed.py: makes products.csv, the store's catalog of 300 products, our own made-up data. Its fixed random seed means everyone gets the same rows.
  • gear.py: the five functions, for you to finish.
  • explore.ipynb: a notebook for looking at the catalog 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: answers a few questions about the catalog with your five functions and prints the answers. 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 catalog. 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 gear.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 top_rated(df, n, min_reviews):
    """Return the n best-rated products that have at least min_reviews reviews.

    Leave out every product with fewer than min_reviews reviews. Sort the rest by rating,
    highest first; when two ratings are the same, the one with more reviews comes first.
    Keep the first n, numbered 0, 1, 2 ... in the returned table's index.

    Ratings 5.0 (2 reviews), 4.8 (40), 4.8 (95) and 4.1 (300), n = 2, min_reviews = 10:
    the 4.8 with 95 reviews, then the 4.8 with 40 reviews, at index 0 and 1.
    """
    raise NotImplementedError("Not built yet.")

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

  1. under_budget(df, max_price) returns the products whose price is max_price or less, in the order they're in. A product priced exactly at the budget counts: with prices 24.99, 50.0, 50.01 and 129.99 and a budget of 50, the first two come back.
  2. in_stock(df, category) returns the products of that category (such as "stoves") with a stock above 0, in the order they're in.
  3. top_rated(df, n, min_reviews) leaves out the products with fewer than min_reviews reviews, sorts the rest by rating from highest to lowest and breaks a tie with the most reviews first, keeps the first n, and numbers them from 0. The docstring above works one example through.
  4. add_price_band(df) returns a new table with a price_band column: budget under 50, mid from 50 up to (not including) 150, and premium from 150 up. So 49.99 is budget, 50.0 and 149.99 are mid, and 150.0 is premium.
  5. sale_prices(df, percent_off) returns a new table with a sale_price column: a product on sale (on_sale is True) costs percent_off percent less, rounded to cents, and every other product keeps its price. With 20 off, 100.0 on sale becomes 80.0, 59.99 on sale becomes 47.99, and 100.0 not on sale stays 100.0.

Each function returns a new table and leaves the one it was given unchanged; the tests check that too. When a function adds a column, start it with result = df.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 17 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 top_rated(df, 2, 10)['sku'] for 5.0 (2 reviews), 4.8 (40), 4.8 (95), 4.1 (300) should give ['TO-3', 'TO-2'], but it gave ['TO-1', 'TO-3'].

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

Hints

  • Count before you trust a filter. In the notebook, (products["price"] <= 50).sum() says how many rows a condition keeps, as Filtering Rows with a Condition does.
  • Two conditions need & and two pairs of parentheses. in_stock is "this category and stock above 0", as Combining Conditions with &, | and ~ shows.
  • Filter, sort, head, renumber. top_rated is the fair top list from Sorting and Top Lists: sort_values with two columns and two directions, then head(n) and reset_index(drop=True).
  • Mind the edges. pd.cut with right=False puts 50.0 in mid and 150.0 in premium, as New Columns from Old: Math, np.where and cut explains; float("inf") is the top edge.
  • One of two values for each row. np.where(df["on_sale"], ..., ...) takes the sale price where it's True and the normal price where it's False. Round the sale price with .round(2).

When you're done

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

1) products: 300
2) products at 50 dollars or less: 16
3) stoves in stock: 33
4) best rated with 20 or more reviews: Ridge Glide Tent
5) its rating and reviews: 5.0 68
6) budget products: 16
7) mid products: 106
8) premium products: 178
9) products on sale: 72
10) catalog total at sale prices: 55252.47

Now look at line 4. With min_reviews of 20, a tent with 68 reviews wins. Try top_rated(products, 3, 1) in the notebook: which products take the top places, and would you trust that list as a shopper?

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-gear-finder), 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-gear-finder.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-gear-finder, 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

A gear finder is a handful of questions asked of one table: which rows, in what order, and with which new columns. Written as tested functions, each answer stays right as the catalog changes.

Key terms

Related