Every exercise in 81_stretch.ipynb, with the solution and why it works. Each answer stays closed until you swear you tried it first. Opening one changes nothing in your notebook; your check still has to go green from your own code. Read the whole notebook, with its lessons.
Stretch S1.1. Days to the census
The task
The datetime module works with dates: datetime.date(2026, 5, 1) is 1 May 2026, and subtracting two dates gives the time between them, whose .days is the number of days. datetime.date.fromisoformat("2026-05-01") reads a date written as year-month-day.
Finish days_until(census_day, today) so that it returns the number of days from today to census_day, both written as YYYY-MM-DD, or 0 when the census day has already passed.
| call | returns |
|---|---|
days_until("2026-05-01", "2026-04-01") |
30 |
days_until("2026-05-01", "2026-06-01") |
0 |
If the check is red: common causes
- A negative number: the census has passed; return 0 then.
- 29 days for February 2028: 2028 is a leap year; subtracting dates handles it, counting by hand does not.
The solution, and why it works
Try it yourself first: the check names the input that failed, and the common causes above cover most red checks. Open this when you have been stuck for ten minutes, or when your check is green and you want to compare.
The idea
Read both texts as dates, subtract, and take the number of days; a census in the past is zero days away, not a negative number.
The function, solved
Copy it with the button on the code's frame, and paste it over all the code in the exercise's cell, so the indentation stays right.
def days_until(census_day, today): census = datetime.date.fromisoformat(census_day) now = datetime.date.fromisoformat(today) return max((census - now).days, 0)Why each part is there
datetime.date.fromisoformat(...)turns"2026-05-01"into a date, which knows the lengths of months and leap years, so the subtraction is right across them.(census - now).daysis the whole number of days between them; it is negative when the census has passed.max(..., 0)turns a negative count into 0 in one step, without anif.
Stretch S1.2. One format for every date
The task
Dates arrive written in different ways. datetime.datetime.strptime(text, format) reads a date in a given format: %Y is a four-digit year, %m a month number, %d a day, %B a month's name. It raises ValueError when the text does not fit the format.
Finish iso_date(text) so that it reads a date written as 2022-01-31, 2022/01/31, 31.01.2022 or January 31, 2022, and returns it as YYYY-MM-DD. Text in none of those formats raises a ValueError with the message not a date: followed by the text.
| call | returns |
|---|---|
iso_date("31.01.2022") |
"2022-01-31" |
iso_date("January 31, 2022") |
"2022-01-31" |
If the check is red: common causes
- A different message for a text that is not a date: the check compares the message,
not a date:and the text. "February 30, 2022"read as a date: it is not one;strptimerefuses it in every format, so the function should raise.
The solution, and why it works
Try it yourself first: the check names the input that failed, and the common causes above cover most red checks. Open this when you have been stuck for ten minutes, or when your check is green and you want to compare.
The idea
Try each known format in turn; the first that reads the text gives the date. Only when none fits does the function raise, with a message that names the text.
The function, solved
Copy it with the button on the code's frame, and paste it over all the code in the exercise's cell, so the indentation stays right.
def iso_date(text): for form in ["%Y-%m-%d", "%Y/%m/%d", "%d.%m.%Y", "%B %d, %Y"]: try: return datetime.datetime.strptime(text.strip(), form).strftime("%Y-%m-%d") except ValueError: continue raise ValueError(f"not a date: {text}")Why each part is there
- The formats are a list, so a new way of writing dates is one more entry, not one more
if. strptimeraisesValueErrorfor a format that does not fit;continuemoves on to the next format..strftime("%Y-%m-%d")writes the date in one format, whatever format it came in.
Stretch S1.3. A herd that keeps count
The task
Finish the class Herd: a farm's livestock, by species. add(species, count) adds animals, remove(species, count) takes them away and raises a ValueError (not enough <species>) when there are not enough, and total() gives the number of animals. Its counts is a dictionary from species to number, with no species at zero.
| calls | counts after them |
|---|---|
h = Herd(); h.add("carabao", 2); h.add("goat", 5); h.remove("goat", 5) |
{"carabao": 2} |
If the check is red: common causes
- A species left at 0 in
counts: delete it when none are left. - A negative count: the check for enough animals must come before the subtraction.
- A different message: the check compares it,
not enough goat.
The solution, and why it works
Try it yourself first: the check names the input that failed, and the common causes above cover most red checks. Open this when you have been stuck for ten minutes, or when your check is green and you want to compare.
The idea
Check before changing anything: if there are not enough animals, raise and leave the counts as they were; otherwise subtract, and drop the species when none are left.
The function, solved
Copy it with the button on the code's frame, and paste it over all the code in the exercise's cell, so the indentation stays right.
def remove(self, species, count): have = self.counts.get(species, 0) if count > have: raise ValueError(f"not enough {species}") if have == count: del self.counts[species] else: self.counts[species] = have - countWhy each part is there
self.counts.get(species, 0)is 0 for a species the herd never had, so removing one raises the same clear error.- The check comes first, so a refused removal changes nothing: the herd never shows a negative count.
- Deleting a species that reaches zero keeps
countsto the species actually there, which the task asks for.