Stretch exercises¶

For when you finish a module early: harder exercises, with less help. Each uses what modules 2 to 6 covered, and one or two things they did not, which the task names. Every one has a check, like the modules' exercises, and its solution and explanation on the companion.

In [1]:
import datetime

import course
from course import check_cases, try_it

S1.1 · Days to the census¶

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
In [2]:
def days_until(census_day, today):
    raise NotImplementedError("Stretch S1.1")  # delete this line when your code is ready
In [3]:
try_it(days_until, "2026-05-01", "2026-04-01")
Out[3]:

days_until('2026-05-01', '2026-04-01'): not written yet. Write your code, delete the raise NotImplementedError line, and run the function's cell.

In [4]:
check_cases("Stretch S1.1", days_until, [(f'days_until("{c}", "{t}")', (c, t)) for c, t in [("2026-05-01", "2026-04-01"), ("2026-05-01", "2026-06-01"), ("2026-05-01", "2026-05-01"), ("2028-03-01", "2028-02-01"), ("2027-01-01", "2026-12-31")]],
            what="dates", hint="Subtract two dates and take `.days`.")
Out[4]:

Stretch S1.1: not attempted yet. Subtract two dates and take .days.

If the check is red: common causes for Stretch S1.1
  • 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.

S1.2 · One format for every date¶

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"
In [5]:
def iso_date(text):
    raise NotImplementedError("Stretch S1.2")  # delete this line when your code is ready
In [6]:
try_it(iso_date, "January 31, 2022")
Out[6]:

iso_date('January 31, 2022'): not written yet. Write your code, delete the raise NotImplementedError line, and run the function's cell.

In [7]:
check_cases("Stretch S1.2", iso_date, [(repr(t), (t,)) for t in ["2022-01-31", "2022/01/31", "31.01.2022", "January 31, 2022", " 2023-12-01 ", "2022,04,04", "February 30, 2022"]],
            what="dates", hint="Try each format; raise only when none fits.", raises=True)
Out[7]:

Stretch S1.2: not attempted yet. Try each format; raise only when none fits.

If the check is red: common causes for Stretch S1.2
  • 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; strptime refuses it in every format, so the function should raise.

S1.3 · A herd that keeps count¶

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}
In [8]:
class Herd:
    """A farm's livestock: how many animals of each species."""

    def __init__(self):
        self.counts = {}

    def add(self, species, count):
        self.counts[species] = self.counts.get(species, 0) + count

    def remove(self, species, count):
        raise NotImplementedError("Stretch S1.3")  # delete this line when your code is ready

    def total(self):
        return sum(self.counts.values())


def run_herd(steps):
    """Make a herd and carry out the steps, ("add" or "remove", species, count); give back its counts and total."""
    herd = Herd()
    for action, species, count in steps:
        getattr(herd, action)(species, count)
    return herd.counts, herd.total()
In [9]:
try_it(run_herd, [("add", "carabao", 2), ("add", "goat", 5), ("remove", "goat", 5)])
Out[9]:

run_herd([('add', 'carabao', 2), ('add', 'goat', 5), ('remove', 'goa…): not written yet. Write your code, delete the raise NotImplementedError line, and run the function's cell.

In [10]:
check_cases(
    "Stretch S1.3", run_herd,
    [("add 2 carabao and 5 goats, remove 5 goats", ([("add", "carabao", 2), ("add", "goat", 5), ("remove", "goat", 5)],)),
     ("remove 2 of 5 goats", ([("add", "goat", 5), ("remove", "goat", 2)],)),
     ("remove a carabao from an empty herd", ([("remove", "carabao", 1)],)),
     ("remove 6 of 5 goats", ([("add", "goat", 5), ("remove", "goat", 6)],))],
    what="herds", hint="Check there are enough before you subtract.", raises=True,
)
Out[10]:

Stretch S1.3: not attempted yet. Check there are enough before you subtract.

If the check is red: common causes for Stretch S1.3
  • 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.