Exercise: Road Trip Planner
Write the five functions behind a road trip planner, with lists, slices, tuples, unpacking and enumerate(), and let pytest's tests call each one to check what it returns.
Apprentice · Python · Updated
A road trip from Chicago to the Grand Canyon is planned, and its planner has every screen designed and no code behind them. You'll write the five functions it needs: one adds a stop before the destination, one adds up the miles, one finds the longest drive, one picks out the first and last stops, and one lists each day's drive. The tests call each function and check what comes back.
Get the exercise code
Open this lesson's GitHub repository, github.com/ask-codey/exercise-python-road-trip-planner, 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-road-trip-planner.git
Git makes a folder, exercise-python-road-trip-planner, 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:
trip.py: the five functions, for you to finish.plan.py: prints the trip's plan with your functions, so you can see them at work. Ready to use.tests/test_trip.py: the tests, which call each function and check what comes back. You don't need to change it.requirements.txtandpytest.ini: the package the tests need, and where pytest finds the tests and your code.
What to do
The planner keeps the trip two ways. stops is a list of the cities in order, from the start to the destination, such as ["Chicago", "Omaha", "Denver", "Moab", "Grand Canyon"]. legs is a list of (city, miles) tuples, one for each day's drive: the city you reach that day and the miles it takes, such as [("Omaha", 470), ("Denver", 540), ("Moab", 355), ("Grand Canyon", 330)].
Every function in trip.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 total_miles(legs):
"""Return the miles of every leg added together.
A trip with no legs has driven 0 miles.
total_miles([("Omaha", 470), ("Denver", 540), ("Moab", 355), ("Grand Canyon", 330)]) -> 1695
total_miles([("Omaha", 470)]) -> 470
total_miles([]) -> 0
"""
raise NotImplementedError("Not built yet.")
In each function, replace the raise NotImplementedError("Not built yet.") line with your own code:
add_stop(stops, city)putscityinto the list right before its last stop, so the destination stays last. Ifcityis already instops, the list stays as it is. This one changes the list it's given, and returns nothing.total_miles(legs)returns the miles of every leg added together, and0when there are no legs.longest_leg(legs)returns the(city, miles)tuple of the leg with the most miles, such as("Denver", 540). When two legs tie, it returns the first of them; when there are no legs, it returnsNone.first_and_last(stops, count=2)returns a tuple of two lists: the firstcountstops and the lastcountstops, such as(["Chicago", "Omaha"], ["Moab", "Grand Canyon"]). When the trip has fewer stops thancount, each list holds the whole trip.itinerary_lines(legs)returns a list of strings, one for each leg, numbered from day 1:"Day 1: Omaha, 470 miles","Day 2: Denver, 540 miles"and so on.
Apart from add_stop, each function returns its answer and changes nothing: the tests read what comes back.
Check your work
Run the tests from the exercise folder, with the virtual environment on:
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 total_miles([]) should return 0, but it returned None. For add_stop, the message says what the list should hold afterward and what it holds.
To see your functions at work, run python plan.py. It prints the trip's plan from your five functions.
Hints
- Work an example through by hand first. Of the four legs, which has the most miles, and what are its city and miles? That pair is what
longest_leghands back. - Insert before the destination.
.insert()puts an item at an index, and a negative index counts from the end. Lists: Keeping Things in Order shows both, andinfor checking first. - Unpack as you loop.
for city, miles in legs:gives each leg's two parts a name. Tuples and Unpacking shows how. - A slice never stops with an error.
stops[:2]andstops[-2:]give what exists, even on a short list. Slicing Lists and Strings has the details. - Number from 1.
enumerate(legs, start=1)hands the loop each day's number with its leg, as Looping Through a List shows, and an f-string builds each line.
When you're done
Every test is green: pytest's last line says 15 passed. And python plan.py prints:
Road trip: Chicago to the Grand Canyon
Stops: ['Chicago', 'Omaha', 'Denver', 'Moab', 'Grand Canyon']
Starts with ['Chicago', 'Omaha'] and ends with ['Moab', 'Grand Canyon']
Day 1: Omaha, 470 miles
Day 2: Denver, 540 miles
Day 3: Moab, 355 miles
Day 4: Grand Canyon, 330 miles
Total: 1695 miles
Longest drive: 540 miles, to Denver
Now look back at longest_leg. It returns a tuple, and plan.py unpacks it with city, miles = longest_leg(legs). What would plan.py have to do instead if the function returned only the miles, and the city had to be found again?
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.
On GitHub, click +, then New repository. Name it (for example
exercise-python-road-trip-planner), choose Public, and click Create repository. Leave out the README: your folder already has one.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-road-trip-planner.git git add . git commit -m "My solution" git push -u origin mainPaste your repo's address, such as
https://github.com/your-name/exercise-python-road-trip-planner, 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
Lists for things in order, tuples for things that belong together, and slices and loops to work through them: these are the shapes most real data takes, and small functions that each do one job with them are what a real planner is made of.