AI Coding Interview Practice Beta

Delivery Scheduler Bug Squash

Four bug reports, written as symptoms, in a small cake delivery scheduler. Find and fix each root cause, and practice not accepting an AI's plausible-but-wrong fix.

Bug squash · Medium · 60-minute time box · Python 3.10+

Quick start

  1. Download the starter repo and unzip it.
  2. Open the folder in your editor, with any AI assistant you like.
  3. Run the tests from the repo's folder: python3 -m unittest discover -s tests. The tests for the stages you haven't done yet fail.
  4. Set a timer for 60 minutes and work through the stages in order.

Stages

  1. Stage 1: Lunchtime slots are broken
  2. Stage 2: Drivers get deliveries after their shift has ended
  3. Stage 3: Route sheets show other drivers' deliveries
  4. Stage 4: Urgent deliveries aren't treated as urgent

What it practices

  • reading unfamiliar code
  • reproducing bugs from symptoms
  • 12-hour time edge cases
  • off-by-one errors in ranges
  • mutable default arguments and aliasing
  • sorting with custom keys
  • verifying AI-written fixes

Similar to

  • Stripe bug-finding round
  • Debugging interviews

The scenario

Crumb & Co. delivers celebration cakes and cafe orders around town. The delivery scheduler is a small Python package of six modules (about 320 lines). It parses delivery windows like 9:00-11:30 and 2pm-4pm, assigns deliveries to the drivers on shift, orders each driver's route by window start and priority, works out ETAs, and prints a route sheet.

It mostly works, but four bug reports have come in. Each one describes what people see, not what's wrong in the code. Your job is to find and fix the root cause of each one. This is the "bug squash" format, like Stripe's bug-finding round and other debugging interviews: you're handed unfamiliar code and a list of symptoms, and you're judged on how methodically you get from symptom to cause.

Time box: 60 minutes. The bugs get subtler as you go. Each one has its own test file and doesn't depend on the others, but work through them in order.

  1. Bug 1: lunchtime slots are broken. Booking 12pm-1:30pm fails with "window ends before it starts", and lunchtime ETAs print as 0:40pm. Done when every time around 12 o'clock, morning or afternoon, parses and prints correctly.
  2. Bug 2: drivers get deliveries after their shift has ended. A 6am-11am driver is given an 11am-1pm delivery. Done when back-to-back windows don't count as overlapping, and genuine overlaps (even a single minute) still do.
  3. Bug 3: route sheets show other drivers' deliveries. Done when every driver's route holds only their own stops, re-running the scheduler starts clean, and pre-loading two drivers from the same list doesn't link them.
  4. Bug 4: urgent deliveries aren't treated as urgent. Done when dispatch hands out URGENT, HIGH, NORMAL, LOW in that order, and within a window the route visits the most urgent stop first.

The README in the download has the full bug reports and the scheduling rules. test_existing.py passes from the start; test_stage1.py to test_stage4.py go with bugs 1 to 4. Run them with python3 -m unittest discover -s tests.

How to work this problem with an AI assistant

Read the rules, then reproduce each symptom yourself. The README's "How it works" section is the spec. Before asking an assistant anything about bug 1, open a Python shell and run parse_window("12pm-1:30pm") and format_time(760). Seeing the actual wrong values tells you where to look, and it gives you a check for later.

Read the failing test before reading the fix. Each stage's tests name the cases that matter, including ones the bug report doesn't mention. Run one file at a time (-p "test_stage2.py") and read the assertion messages. Then give the assistant the symptom, the failing test and the relevant modules, and ask it to explain the cause before it changes anything.

Good prompts for this codebase:

  • "Here's timeutil.py. What do parse_time and format_time return for 12am, 12:30am, 12pm, 12:30pm and 1pm? Explain any that are wrong before suggesting a fix."
  • "The docstring says windows are half-open. Does TimeWindow.overlaps agree? Check it with back-to-back windows in both argument orders."
  • "Two Driver objects created without stops seem to share deliveries. Explain why, and also what happens when two drivers are created from the same list."
  • "Find every place in the package that sorts by Priority, and tell me what order the four priorities actually end up in."

Verify, then look for the same bug elsewhere. Assistants are good at fixing the line you point at and bad at noticing the same mistake two files away. After each fix, search for the pattern (.value, <=, mutable defaults) and run all the tests, not just the stage you're on.

Self-check rubric

Here's what interviewers look for in debugging rounds, with or without AI. Be honest about which column you were in.

Area Strong signals Weak signals
Understanding the codebase Reads the spec and the relevant module before changing anything. Can say which function each symptom comes from, and why. Edits the first function whose name matches the bug report. Can't explain how dispatch and routing fit together.
Correctness Fixes the root cause: both halves of the 12 o'clock bug, both sides of the overlap check, the aliasing as well as the shared default, and both priority sorts. Fixes the reported symptom only (12pm but not 12am; the route but not dispatch). Over-corrects (rejects genuine partial overlaps).
Tests and verification Reproduces each bug before fixing it, reads failing assertions, runs the whole suite after each fix, and can name a case the tests check that the report didn't mention. Iterates on AI patches until the tests go green without knowing why they failed. Edits tests.
Code quality Minimal, targeted fixes. Names the concept in code (a rank for priorities; a copy of the stops list) and leaves a short comment where the trap was. Rewrites working modules. Adds special cases (if hour == 12) all over the place instead of fixing the rule.
Use of AI Asks the assistant to explain before fixing, gives it the spec, and pushes back on "fixes" that only cover the example. Pastes the bug report and accepts the first patch. Can't explain the diff.
Communication For each bug, states the symptom, the cause, the fix, and how they verified it, in a sentence or two each. "I changed some things and the tests pass."

Walkthrough

Show the walkthrough (spoilers)

Bug 1: lunchtime slots are broken

Root cause. Two halves of the same misunderstanding of the 12-hour clock: 12am is hour 0, and 12pm is hour 12. parse_time adds 12 to every pm hour, so 12pm becomes 24:00 and 12am stays at noon. format_time prints hour % 12, which is 0 for both the noon and the midnight hour. The two bugs partly cancel out: 11am-12pm is stored as ending at midnight, and printed as 11:00am-0:00pm.

# parse_time
hour = hour % 12 + (12 if suffix == "pm" else 0)

# format_time
return f"{hour % 12 or 12}:{minute:02d}{suffix}"

Plausible-but-wrong AI fixes. if suffix == "pm" and hour != 12 fixes noon but leaves 12am as noon. Fixing only format_time is worse: the route sheet then prints 11:00am-12:00pm, which looks right, while the window still ends at midnight. Special-casing noon in the formatter leaves 0:45am. The tests catch all of these, including a check that every minute of the day survives format_time then parse_time.

Weak prompt: "12pm-1:30pm says the window ends before it starts. Fix it."
Strong prompt: "In timeutil.py, show what parse_time and format_time give for 12am, 12:30am, 12pm, 12:30pm and 1pm. Fix both so that every minute of the day round-trips through format_time then parse_time."

Bug 2: drivers get deliveries after their shift has ended

Root cause. The docstring says windows are half-open, [start, end), but overlaps compares with <= on both sides, which treats them as closed. A 6am-11am shift and an 11am-1pm delivery share only the instant 11:00, and that counts as an overlap, so the driver whose shift has ended is eligible.

def overlaps(self, other: TimeWindow) -> bool:
    return self.start < other.end and other.start < self.end

Plausible-but-wrong AI fixes. Making only one comparison strict fixes the reported morning case but not the afternoon one (an 11am-1pm delivery and a 1pm shift), because the result now depends on argument order. "The delivery has to fit inside the shift" rejects real partial overlaps. Patching Driver.can_take to check delivery.start < shift.end forgets the other end. The tests check both argument orders, a one-minute overlap, and partial overlaps that must still be assigned.

Weak prompt: "Sam gets deliveries after 11am. Fix dispatch."
Strong prompt: "Windows are half-open per the README. Check TimeWindow.overlaps against that for back-to-back windows, a one-minute overlap and containment, in both argument orders. Fix it there, not in the dispatcher."

Bug 3: route sheets show other drivers' deliveries

Root cause. Driver.__init__ has a mutable default argument, stops: list[Delivery] = []. Python evaluates that default once, when the function is defined, so every driver created without stops shares one list, across drivers and across scheduler runs. There's a second, quieter bug: self.stops = stops keeps a reference to the caller's list, so two drivers pre-loaded from the same standing-order list are linked too.

def __init__(self, name: str, shift: TimeWindow, max_stops: int = 8,
             stops: Iterable[Delivery] = ()) -> None:
    ...
    self.stops: list[Delivery] = list(stops)  # always a fresh list

Plausible-but-wrong AI fixes. The textbook fix, stops=None then self.stops = stops if stops is not None else [], cures the shared default but still aliases a list you pass in. stops or [] has the same problem. Copying the lists inside dispatch() only hides the bug from one caller. The pre-loaded-drivers test catches all three.

Weak prompt: "Fix the mutable default argument in Driver."
Strong prompt: "Drivers share deliveries in two situations: created with no stops, and created from the same list. Explain both, then fix Driver so each driver always owns its own list and the caller's list is never modified."

Bug 4: urgent deliveries aren't treated as urgent

Root cause. Priority's values are the strings the order system exports, and both dispatch and order_stops sort on priority.value. Strings sort alphabetically: "high" < "low" < "normal" < "urgent". So URGENT comes last, and LOW comes before NORMAL. The code reads naturally, which is why it's the hardest bug here, and the same mistake is in two files.

class Priority(Enum):
    ...
    @property
    def rank(self) -> int:
        """0 for the most urgent. Sort by this: sorting by .value is alphabetical."""
        return _RANKS[self]

_RANKS = {Priority.URGENT: 0, Priority.HIGH: 1, Priority.NORMAL: 2, Priority.LOW: 3}

# dispatch.py
queue = sorted(deliveries, key=lambda d: (d.priority.rank, d.window.start, d.id))
# route.py
return sorted(deliveries, key=lambda d: (d.window.start, d.priority.rank, d.id))

Plausible-but-wrong AI fixes. Fixing only the route (the symptom the owner noticed first). Adding reverse=True to the whole sort, which also reverses the windows. Sorting by priority descending in a separate pass before a stable sort by window. That gives urgent, normal, low, high, which passes an "urgent before normal" test but puts HIGH last. Changing the enum values to integers breaks Priority.parse for the CSV loader. The stage 4 tests check every pair of priorities, in both dispatch and routing.

Weak prompt: "Urgent stops are visited last. Fix the route sort."
Strong prompt: "Find every sort that involves Priority. For each one, show the order URGENT, HIGH, NORMAL and LOW actually come out in. Then fix them all with one explicit ranking, without changing the enum's string values (the CSV loader depends on them)."

Files in the starter repo

Here's everything in the starter repo, so you can look around before you download it. Click a file to open it.

README.md 87 lines
# Crumb & Co. delivery scheduler: bug squash

Crumb & Co. delivers celebration cakes and cafe orders around town. This module reads the day's deliveries
from the order system, assigns them to the drivers on shift, orders each driver's route, and prints a route
sheet with ETAs. It mostly works, but four bug reports have come in from the shop. Find and fix the root
cause of each one.

## Running the tests

Python 3.10 or newer, standard library only (nothing to install). From this folder:

    python3 -m unittest discover -s tests

To run one bug's tests: `python3 -m unittest discover -s tests -p "test_stage1.py"`

- `tests/test_existing.py` covers behaviour that already works. It passes now; keep it passing.
- `tests/test_stage1.py` to `tests/test_stage4.py` go with bugs 1 to 4. Each fails until its bug is fixed,
  and each only exercises its own bug, so you can fix them in any order. The tests cover the reported case
  and related cases the report doesn't mention: fix the cause, not just the one symptom.

## Time box and rules

60 minutes. The bugs get subtler as you go; bug 4 is the hardest. Work through them in order.

Use any editor and any AI assistant you like. In a real AI-allowed interview you'd be expected to explain
and verify everything the AI writes, so practice that too.

Change anything under `delivery/`, but don't edit the tests. For each fix, be ready to say what the root
cause was and why your change fixes it.

## How it works

| Module | What it does |
|---|---|
| `delivery/timeutil.py` | `parse_time`, `format_time`, `TimeWindow`, `parse_window` |
| `delivery/models.py` | `Priority`, `Delivery`, `Driver` |
| `delivery/loader.py` | Reads the order system's CSV export |
| `delivery/dispatch.py` | `dispatch`: assigns deliveries to drivers; `build_roster` |
| `delivery/route.py` | `order_stops` and `plan_route`: stop order and ETAs |
| `delivery/manifest.py` | `render_manifest`: the printed route sheet |

The rules, as the shop wants them:

- Times are minutes after midnight. People type "9:00", "14:30", "9am" or "2:45 PM".
- Windows are half-open: "9:00-10:00" covers 9:00 up to, but not including, 10:00. So back-to-back windows
  don't overlap.
- A driver can take a delivery if they have room on their route (`max_stops`) and their shift overlaps the
  delivery window by at least one minute.
- Dispatch hands out deliveries most urgent first (URGENT, then HIGH, NORMAL, LOW), then by earliest window
  start, then by id. Each goes to the eligible driver with the fewest stops (ties go to whoever is first on
  the roster). If no driver can take it, it's left unassigned.
- A route visits stops by window start, then most urgent first, then id. Travel takes 15 minutes from the
  bakery, 10 minutes within a zone and 25 between zones, and each stop takes 10 minutes. A driver who's early
  waits for the window to open. A stop is late if the driver arrives after the window ends.

## Bug 1: lunchtime slots are broken

> From: the front counter
>
> Customers who book the 12pm-1:30pm slot get an error: "window ends before it starts". The 11am-12pm slot
> goes through, but the route sheet prints its window as "11:00am-0:00pm", and lunchtime ETAs show up as
> things like "0:40pm". Ops thinks anything around 12 o'clock is suspect, morning or afternoon.

## Bug 2: drivers get deliveries after their shift has ended

> From: dispatch
>
> Sam's shift is 6am-11am, but the scheduler keeps giving him deliveries in the 11am-1pm slot, after he's
> gone home, even when Priya (on from 11am) is free. Afternoon drivers who start at 1pm are also being handed
> 11am-1pm deliveries they can't possibly make.

## Bug 3: route sheets show other drivers' deliveries

> From: the drivers
>
> On days with more than one driver, every route sheet lists every delivery of the day, and we hit the
> max-stops limit far too early. When the scheduler is re-run after a late order comes in, deliveries from
> the first run show up again. And since we started pre-loading the standing cafe order onto both morning
> drivers (from the same starting list), each of us sees the other's deliveries.

## Bug 4: urgent deliveries aren't treated as urgent

> From: the owner
>
> On busy days, when there aren't enough drivers, some URGENT cakes are left unassigned while LOW-priority
> deliveries get a driver. And when several deliveries share a window, the urgent one is often visited last,
> so the birthday cake turns up at the end of the window.
delivery/__init__.py 10 lines
"""Delivery scheduling for Crumb & Co.'s cake deliveries.

Modules:
    timeutil   parse and format times of day and delivery windows
    models     Priority, Delivery and Driver
    loader     read the day's deliveries from the order system's CSV export
    dispatch   assign deliveries to the drivers on shift
    route      order each driver's stops and work out ETAs
    manifest   the printed route sheet each driver takes with them
"""
delivery/dispatch.py 42 lines
"""Assign the day's deliveries to the drivers on shift."""

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Iterable, Mapping, Sequence

from delivery.models import Delivery, Driver
from delivery.timeutil import parse_window


@dataclass
class DispatchResult:
    # Driver name -> the deliveries this run gave them, in the order they were assigned.
    assignments: dict[str, list[Delivery]] = field(default_factory=dict)
    unassigned: list[Delivery] = field(default_factory=list)


def build_roster(shifts: Mapping[str, str], max_stops: int = 8) -> list[Driver]:
    """Drivers from {"Sam": "6am-11am", ...}, in roster order."""
    return [Driver(name, parse_window(shift), max_stops) for name, shift in shifts.items()]


def dispatch(deliveries: Iterable[Delivery], drivers: Sequence[Driver]) -> DispatchResult:
    """Give each delivery to a driver who can take it.

    Deliveries are handed out most urgent first, then by earliest window
    start, then by id, so that when we're short of drivers it's the least
    urgent deliveries that wait. Each one goes to the eligible driver with
    the fewest stops so far (ties go to whoever is earlier on the roster).
    """
    queue = sorted(deliveries, key=lambda d: (d.priority.value, d.window.start, d.id))
    result = DispatchResult(assignments={driver.name: [] for driver in drivers})
    for delivery in queue:
        eligible = [driver for driver in drivers if driver.can_take(delivery)]
        if not eligible:
            result.unassigned.append(delivery)
            continue
        chosen = min(eligible, key=lambda driver: len(driver.stops))
        chosen.assign(delivery)
        result.assignments[chosen.name].append(delivery)
    return result
delivery/loader.py 46 lines
"""Read the day's deliveries from the order system's CSV export.

The export has a header row: id,customer,zone,window,priority
(priority may be blank, which means normal).
"""

from __future__ import annotations

import csv
import io
from typing import Mapping

from delivery.models import Delivery, Priority
from delivery.timeutil import parse_window

REQUIRED_FIELDS = ("id", "customer", "zone", "window")


def parse_delivery(record: Mapping[str, str | None]) -> Delivery:
    missing = [name for name in REQUIRED_FIELDS if not (record.get(name) or "").strip()]
    if missing:
        raise ValueError(f"missing {', '.join(missing)}")
    return Delivery(
        id=record["id"].strip(),
        customer=record["customer"].strip(),
        zone=record["zone"].strip().lower(),
        window=parse_window(record["window"]),
        priority=Priority.parse(record.get("priority") or "normal"),
    )


def load_deliveries(csv_text: str) -> list[Delivery]:
    """Parse the CSV export. Errors say which line was wrong, so ops can fix the order."""
    deliveries = []
    seen: set[str] = set()
    reader = csv.DictReader(io.StringIO(csv_text.strip()))
    for line_number, record in enumerate(reader, start=2):
        try:
            delivery = parse_delivery(record)
        except ValueError as error:
            raise ValueError(f"line {line_number}: {error}") from None
        if delivery.id in seen:
            raise ValueError(f"line {line_number}: duplicate delivery id {delivery.id}")
        seen.add(delivery.id)
        deliveries.append(delivery)
    return deliveries
delivery/manifest.py 21 lines
"""The printed route sheet each driver takes with them."""

from __future__ import annotations

from delivery.models import Driver
from delivery.route import Stop
from delivery.timeutil import format_time, format_window


def render_manifest(driver: Driver, stops: list[Stop]) -> str:
    lines = [f"Route for {driver.name} (shift {format_window(driver.shift)})"]
    for number, stop in enumerate(stops, start=1):
        delivery = stop.delivery
        flag = "  LATE" if stop.late else ""
        lines.append(
            f"{number:>2}. {format_time(stop.eta):>7}  {delivery.id:<6} {delivery.customer:<12} "
            f"{delivery.zone:<8} {delivery.priority.name:<6}  window {format_window(delivery.window)}{flag}"
        )
    late = sum(1 for stop in stops if stop.late)
    lines.append(f"{len(stops)} stops, {late} late")
    return "\n".join(lines)
delivery/models.py 66 lines
"""Deliveries and drivers."""

from __future__ import annotations

from dataclasses import dataclass
from enum import Enum

from delivery.timeutil import TimeWindow


class Priority(Enum):
    """How urgent a delivery is, most urgent first.

    The values are the strings the order system exports.
    """

    URGENT = "urgent"
    HIGH = "high"
    NORMAL = "normal"
    LOW = "low"

    @classmethod
    def parse(cls, text: str) -> Priority:
        try:
            return cls(text.strip().lower())
        except ValueError:
            raise ValueError(f"unknown priority {text!r}") from None


@dataclass(frozen=True)
class Delivery:
    id: str
    customer: str
    zone: str
    window: TimeWindow
    priority: Priority = Priority.NORMAL


class Driver:
    """A driver on today's roster and the stops on their route.

    `stops` can be pre-loaded with standing orders (the morning cafe run,
    say) before the dispatcher adds the day's deliveries.
    """

    def __init__(
        self,
        name: str,
        shift: TimeWindow,
        max_stops: int = 8,
        stops: list[Delivery] = [],
    ) -> None:
        self.name = name
        self.shift = shift
        self.max_stops = max_stops
        self.stops = stops

    def can_take(self, delivery: Delivery) -> bool:
        """Room on the route, and on shift for at least part of the delivery window."""
        return len(self.stops) < self.max_stops and self.shift.overlaps(delivery.window)

    def assign(self, delivery: Delivery) -> None:
        self.stops.append(delivery)

    def __repr__(self) -> str:
        return f"Driver({self.name!r}, {len(self.stops)} stops)"
delivery/route.py 51 lines
"""Order a driver's stops for the day and work out an ETA for each one.

Travel times are rough averages from the last three months of deliveries:
15 minutes from the bakery to any zone, 10 minutes within a zone and 25
minutes between zones. Every stop takes 10 minutes (carry the cake in, get
a signature). A driver who arrives before a window opens waits for it.
"""

from __future__ import annotations

from dataclasses import dataclass
from typing import Iterable

from delivery.models import Delivery, Driver

FROM_BAKERY_MINUTES = 15
SAME_ZONE_MINUTES = 10
OTHER_ZONE_MINUTES = 25
STOP_MINUTES = 10


@dataclass(frozen=True)
class Stop:
    delivery: Delivery
    eta: int  # minutes after midnight
    late: bool  # arriving right at the end of the window still counts as on time


def order_stops(deliveries: Iterable[Delivery]) -> list[Delivery]:
    """The order to visit stops in: by window start, then most urgent first, then id."""
    return sorted(deliveries, key=lambda d: (d.window.start, d.priority.value, d.id))


def travel_minutes(from_zone: str | None, to_zone: str) -> int:
    if from_zone is None:
        return FROM_BAKERY_MINUTES
    return SAME_ZONE_MINUTES if from_zone == to_zone else OTHER_ZONE_MINUTES


def plan_route(driver: Driver, depart_at: int | None = None) -> list[Stop]:
    """ETAs for the driver's stops, leaving the bakery at `depart_at` (default: start of shift)."""
    clock = driver.shift.start if depart_at is None else depart_at
    here: str | None = None
    stops = []
    for delivery in order_stops(driver.stops):
        arrival = clock + travel_minutes(here, delivery.zone)
        eta = max(arrival, delivery.window.start)
        stops.append(Stop(delivery, eta, late=eta > delivery.window.end))
        clock = eta + STOP_MINUTES
        here = delivery.zone
    return stops
delivery/timeutil.py 86 lines
"""Times of day and delivery windows.

Times are stored as minutes after midnight (0-1439). Customers and the ops
team type times in a mix of 24-hour ("14:30") and 12-hour ("2:30pm",
"2 PM", "9am") formats, so we accept both.
"""

from __future__ import annotations

import re
from dataclasses import dataclass

MINUTES_PER_DAY = 24 * 60

_TIME = re.compile(r"^(\d{1,2})(?::(\d{2}))?\s*([ap]m)?$", re.IGNORECASE)
_WINDOW_SEPARATOR = re.compile(r"\s*(?:-|–|\bto\b)\s*", re.IGNORECASE)


def parse_time(text: str) -> int:
    """Parse "9:00", "14:30", "9am", "2:45 PM" and so on into minutes after midnight."""
    match = _TIME.match(text.strip())
    if not match:
        raise ValueError(f"can't read the time {text!r}")
    hour = int(match.group(1))
    minute = int(match.group(2) or 0)
    suffix = (match.group(3) or "").lower()
    if minute > 59:
        raise ValueError(f"can't read the time {text!r}")

    if suffix:
        if not 1 <= hour <= 12:
            raise ValueError(f"{text!r}: 12-hour times run from 1 to 12")
        if suffix == "pm":
            hour += 12
    else:
        if match.group(2) is None:
            raise ValueError(f"{text!r} is ambiguous: write 9am, 9pm or 09:00")
        if hour > 23:
            raise ValueError(f"can't read the time {text!r}")
    return hour * 60 + minute


def format_time(minutes: int) -> str:
    """Format minutes after midnight the way the drivers like it: "9:05am", "2:30pm"."""
    hour, minute = divmod(minutes, 60)
    suffix = "am" if hour < 12 else "pm"
    return f"{hour % 12}:{minute:02d}{suffix}"


@dataclass(frozen=True)
class TimeWindow:
    """A span of the day, [start, end) in minutes after midnight.

    The end is exclusive: "9:00-10:00" covers 9:00 up to, but not including,
    10:00. So back-to-back windows ("9:00-10:00" and "10:00-11:00") don't
    overlap.
    """

    start: int
    end: int

    def __post_init__(self) -> None:
        if self.start >= self.end:
            raise ValueError("window ends before it starts")
        if self.start < 0 or self.end > MINUTES_PER_DAY:
            raise ValueError("window must fit inside one day")

    @property
    def minutes(self) -> int:
        return self.end - self.start

    def overlaps(self, other: TimeWindow) -> bool:
        """True if the two windows share at least one minute."""
        return self.start <= other.end and other.start <= self.end


def parse_window(text: str) -> TimeWindow:
    """Parse "9:00-11:30", "2pm-4pm", "2pm - 4pm" or "9am to 11am"."""
    parts = _WINDOW_SEPARATOR.split(text.strip())
    if len(parts) != 2 or not all(parts):
        raise ValueError(f"can't read the window {text!r}: expected something like 2pm-4pm")
    return TimeWindow(parse_time(parts[0]), parse_time(parts[1]))


def format_window(window: TimeWindow) -> str:
    return f"{format_time(window.start)}-{format_time(window.end)}"
tests/test_existing.py 205 lines
"""Behaviour that already works. Keep these passing while you fix the bugs."""

import unittest

from delivery.dispatch import dispatch
from delivery.loader import load_deliveries, parse_delivery
from delivery.manifest import render_manifest
from delivery.models import Delivery, Driver, Priority
from delivery.route import order_stops, plan_route, travel_minutes
from delivery.timeutil import TimeWindow, format_time, format_window, parse_time, parse_window


def delivery(delivery_id, window, zone="central", priority=Priority.NORMAL, customer="Ana Lopez"):
    return Delivery(delivery_id, customer, zone, parse_window(window), priority)


def driver(name, shift, *standing, max_stops=8):
    return Driver(name, parse_window(shift), max_stops, stops=list(standing))


def ids(deliveries):
    return [d.id for d in deliveries]


class TestParseTime(unittest.TestCase):
    def test_24_hour(self):
        for text, minutes in [("9:00", 540), ("09:05", 545), ("14:30", 870), ("0:15", 15), ("23:59", 1439)]:
            with self.subTest(text=text):
                self.assertEqual(parse_time(text), minutes)

    def test_12_hour(self):
        for text, minutes in [("9am", 540), ("9 AM", 540), ("2pm", 840), ("2:45 pm", 885),
                              ("11:59pm", 1439), (" 7am ", 420), ("1am", 60), ("1:30PM", 810)]:
            with self.subTest(text=text):
                self.assertEqual(parse_time(text), minutes)

    def test_rejects_nonsense(self):
        for text in ["", "9", "24:00", "9:60", "13pm", "0am", "noon", "9:5", "9.30am"]:
            with self.subTest(text=text), self.assertRaises(ValueError):
                parse_time(text)


class TestFormatTime(unittest.TestCase):
    def test_format(self):
        for minutes, text in [(540, "9:00am"), (545, "9:05am"), (870, "2:30pm"), (1439, "11:59pm"),
                              (60, "1:00am"), (780, "1:00pm"), (659, "10:59am")]:
            with self.subTest(minutes=minutes):
                self.assertEqual(format_time(minutes), text)


class TestWindows(unittest.TestCase):
    def test_parse_window_formats(self):
        self.assertEqual(parse_window("9:00-11:30"), TimeWindow(540, 690))
        self.assertEqual(parse_window("2pm-4pm"), TimeWindow(840, 960))
        self.assertEqual(parse_window(" 2pm - 4pm "), TimeWindow(840, 960))
        self.assertEqual(parse_window("9am to 11am"), TimeWindow(540, 660))
        self.assertEqual(parse_window("8:00–9:30"), TimeWindow(480, 570))

    def test_bad_windows(self):
        for text in ["4pm-2pm", "9am", "9am-9am", "9am-", "9am-10am-11am"]:
            with self.subTest(text=text), self.assertRaises(ValueError):
                parse_window(text)

    def test_overlapping_and_separate_windows(self):
        morning, late_morning = parse_window("9:00-11:00"), parse_window("10:00-13:00")
        afternoon, all_day = parse_window("15:00-16:00"), parse_window("6:00-18:00")
        self.assertTrue(morning.overlaps(late_morning))
        self.assertTrue(late_morning.overlaps(morning))
        self.assertFalse(morning.overlaps(afternoon))
        self.assertFalse(afternoon.overlaps(morning))
        self.assertTrue(all_day.overlaps(afternoon))
        self.assertTrue(afternoon.overlaps(all_day))

    def test_format_window(self):
        self.assertEqual(format_window(parse_window("14:00-16:30")), "2:00pm-4:30pm")
        self.assertEqual(parse_window("9am-11am").minutes, 120)


class TestLoader(unittest.TestCase):
    CSV = """id,customer,zone,window,priority
D1,Ana Lopez,Central,9am-11am,high
D2,Ben Okafor,north,2pm-4pm,
D3,Cafe Rosa,east,7:30-8:30,LOW
"""

    def test_load(self):
        d1, d2, d3 = load_deliveries(self.CSV)
        self.assertEqual(d1, Delivery("D1", "Ana Lopez", "central", TimeWindow(540, 660), Priority.HIGH))
        self.assertEqual(d2.priority, Priority.NORMAL)
        self.assertEqual(d3.window, TimeWindow(450, 510))
        self.assertEqual(d3.priority, Priority.LOW)

    def test_errors_name_the_line(self):
        cases = {
            "id,customer,zone,window\nD1,Ana,central,9am-11am\nD2,Ben,,9am-11am\n": "line 3: missing zone",
            "id,customer,zone,window\nD1,Ana,central,11am-9am\n": "line 2: window ends before it starts",
            "id,customer,zone,window\nD1,Ana,central,9am-11am\nD1,Ben,north,2pm-3pm\n": "line 3: duplicate",
            "id,customer,zone,window,priority\nD1,Ana,central,9am-11am,asap\n": "line 2: unknown priority",
        }
        for text, message in cases.items():
            with self.subTest(message=message):
                with self.assertRaises(ValueError) as caught:
                    load_deliveries(text)
                self.assertIn(message, str(caught.exception))

    def test_priority_parse(self):
        self.assertEqual(Priority.parse(" HIGH "), Priority.HIGH)
        self.assertEqual(Priority.parse("Urgent"), Priority.URGENT)
        self.assertEqual(parse_delivery({"id": "D9", "customer": "Ana", "zone": "west",
                                         "window": "9am-10am"}).priority, Priority.NORMAL)


class TestDispatch(unittest.TestCase):
    def test_one_driver_takes_everything_in_priority_then_time_order(self):
        cafe = delivery("D100", "6:30-7:00", customer="Cafe Rosa")
        sam = driver("Sam", "6:00-15:00", cafe)
        deliveries = [delivery("D3", "10:00-11:00"), delivery("D1", "8:00-9:00", priority=Priority.HIGH),
                      delivery("D2", "9:00-10:00")]
        result = dispatch(deliveries, [sam])
        self.assertEqual(ids(result.assignments["Sam"]), ["D1", "D2", "D3"])
        self.assertEqual(ids(sam.stops), ["D100", "D1", "D2", "D3"])
        self.assertEqual(result.unassigned, [])

    def test_capacity(self):
        sam = driver("Sam", "6:00-15:00", max_stops=2)
        result = dispatch([delivery("D1", "9:00-10:00"), delivery("D2", "8:00-9:00"),
                           delivery("D3", "13:00-14:00")], [sam])
        self.assertEqual(ids(sam.stops), ["D2", "D1"])
        self.assertEqual(ids(result.unassigned), ["D3"])

    def test_spreads_work_to_the_driver_with_fewest_stops(self):
        ana, ben = driver("Ana", "6:00-15:00"), driver("Ben", "6:00-15:00")
        result = dispatch([delivery(f"D{n}", f"{8 + n}:00-{9 + n}:00") for n in range(1, 5)], [ana, ben])
        self.assertEqual(ids(result.assignments["Ana"]), ["D1", "D3"])
        self.assertEqual(ids(result.assignments["Ben"]), ["D2", "D4"])

    def test_standing_orders_count_towards_fewest_stops(self):
        ana = driver("Ana", "6:00-15:00", delivery("S1", "6:30-7:00"), delivery("S2", "7:00-7:30"))
        ben = driver("Ben", "6:00-15:00")
        result = dispatch([delivery("D1", "9:00-10:00"), delivery("D2", "10:00-11:00")], [ana, ben])
        self.assertEqual(ids(result.assignments["Ben"]), ["D1", "D2"])

    def test_high_priority_goes_first_when_short_of_drivers(self):
        sam = driver("Sam", "6:00-15:00", max_stops=1)
        result = dispatch([delivery("D1", "8:00-9:00", priority=Priority.LOW),
                           delivery("D2", "14:00-15:00", priority=Priority.HIGH)], [sam])
        self.assertEqual(ids(sam.stops), ["D2"])
        self.assertEqual(ids(result.unassigned), ["D1"])

    def test_only_drivers_on_shift(self):
        early, late = driver("Early", "6:00-11:00"), driver("Late", "13:00-19:00")
        result = dispatch([delivery("D1", "16:00-18:00"), delivery("D2", "7:00-9:00")], [early, late])
        self.assertEqual(ids(result.assignments["Early"]), ["D2"])
        self.assertEqual(ids(result.assignments["Late"]), ["D1"])
        result = dispatch([delivery("D3", "19:30-21:00")], [early, late])
        self.assertEqual(ids(result.unassigned), ["D3"])


class TestRoute(unittest.TestCase):
    def test_travel_times(self):
        self.assertEqual(travel_minutes(None, "north"), 15)
        self.assertEqual(travel_minutes("north", "north"), 10)
        self.assertEqual(travel_minutes("north", "east"), 25)

    def test_order_by_window_start_then_id(self):
        stops = [delivery("D3", "9:00-10:00"), delivery("D1", "10:00-11:00"), delivery("D2", "9:00-11:00")]
        self.assertEqual(ids(order_stops(stops)), ["D2", "D3", "D1"])

    def test_etas_wait_for_the_window_to_open(self):
        sam = driver("Sam", "7:00-11:00",
                     delivery("D102", "9:30-10:30", zone="north", priority=Priority.HIGH),
                     delivery("D101", "8:00-9:00"),
                     delivery("D103", "9:00-9:30", zone="north", priority=Priority.LOW))
        stops = plan_route(sam)
        self.assertEqual([(s.delivery.id, s.eta, s.late) for s in stops],
                         [("D101", 480, False), ("D103", 540, False), ("D102", 570, False)])

    def test_late_stops_and_arriving_at_the_end_of_a_window(self):
        sam = driver("Sam", "9:45-15:00", delivery("D201", "9:00-10:00"),
                     delivery("D202", "9:30-10:15", zone="east"))
        stops = plan_route(sam)
        self.assertEqual([(s.eta, s.late) for s in stops], [(600, False), (635, True)])

    def test_depart_at(self):
        sam = driver("Sam", "7:00-11:00", delivery("D1", "7:00-9:00"))
        self.assertEqual(plan_route(sam, depart_at=480)[0].eta, 495)


class TestManifest(unittest.TestCase):
    def test_route_sheet(self):
        sam = driver("Sam", "7:00-11:00",
                     delivery("D102", "9:30-10:30", zone="north", priority=Priority.HIGH, customer="Ben Okafor"),
                     delivery("D101", "8:00-9:00"),
                     delivery("D103", "9:00-9:15", zone="east", priority=Priority.LOW, customer="Cafe Rosa"))
        self.assertEqual(render_manifest(sam, plan_route(sam)), "\n".join([
            "Route for Sam (shift 7:00am-11:00am)",
            " 1.  8:00am  D101   Ana Lopez    central  NORMAL  window 8:00am-9:00am",
            " 2.  9:00am  D103   Cafe Rosa    east     LOW     window 9:00am-9:15am",
            " 3.  9:35am  D102   Ben Okafor   north    HIGH    window 9:30am-10:30am",
            "3 stops, 0 late",
        ]))


if __name__ == "__main__":
    unittest.main()
tests/test_stage1.py 66 lines
"""Bug 1: lunchtime slots are broken (see README)."""

import unittest

from delivery.loader import load_deliveries
from delivery.manifest import render_manifest
from delivery.models import Driver
from delivery.route import plan_route
from delivery.timeutil import TimeWindow, format_time, format_window, parse_time, parse_window


class TestTwelveOClock(unittest.TestCase):
    def test_parse_noon_and_midnight(self):
        for text, minutes in [("12pm", 720), ("12:30pm", 750), ("12 PM", 720), ("12:59pm", 779),
                              ("12am", 0), ("12:45am", 45), ("12:00", 720), ("0:30", 30)]:
            with self.subTest(text=text):
                self.assertEqual(parse_time(text), minutes)

    def test_hours_either_side_of_twelve(self):
        for text, minutes in [("11:59am", 719), ("1pm", 780), ("11:30pm", 1410), ("1:05am", 65)]:
            with self.subTest(text=text):
                self.assertEqual(parse_time(text), minutes)

    def test_format_noon_and_midnight(self):
        for minutes, text in [(720, "12:00pm"), (750, "12:30pm"), (0, "12:00am"), (45, "12:45am"),
                              (719, "11:59am"), (780, "1:00pm")]:
            with self.subTest(minutes=minutes):
                self.assertEqual(format_time(minutes), text)

    def test_every_minute_round_trips(self):
        for minutes in range(24 * 60):
            text = format_time(minutes)
            self.assertEqual(parse_time(text), minutes, f"{minutes} formats as {text!r}")

    def test_lunch_windows(self):
        self.assertEqual(parse_window("12pm-1:30pm"), TimeWindow(720, 810))
        self.assertEqual(parse_window("11am-12pm"), TimeWindow(660, 720))
        self.assertEqual(parse_window("11:30am-12:30pm"), TimeWindow(690, 750))
        self.assertEqual(format_window(parse_window("11am-12pm")), "11:00am-12:00pm")


class TestLunchRoute(unittest.TestCase):
    def test_route_sheet_for_a_lunchtime_run(self):
        lunch = load_deliveries("""id,customer,zone,window,priority
L1,Ana Lopez,central,12pm-1:30pm,normal
L2,Ben Okafor,central,11am-12pm,normal
""")
        sam = Driver("Sam", parse_window("10:30am-2:30pm"), stops=list(lunch))
        self.assertEqual(render_manifest(sam, plan_route(sam)), "\n".join([
            "Route for Sam (shift 10:30am-2:30pm)",
            " 1. 11:00am  L2     Ben Okafor   central  NORMAL  window 11:00am-12:00pm",
            " 2. 12:00pm  L1     Ana Lopez    central  NORMAL  window 12:00pm-1:30pm",
            "2 stops, 0 late",
        ]))

    def test_late_flag_around_noon(self):
        sam = Driver("Sam", parse_window("11:50am-3pm"),
                     stops=list(load_deliveries("id,customer,zone,window\nL3,Cafe Rosa,east,11am-12pm\n")))
        (stop,) = plan_route(sam)
        self.assertEqual(stop.eta, 725)
        self.assertTrue(stop.late)
        self.assertEqual(format_time(stop.eta), "12:05pm")


if __name__ == "__main__":
    unittest.main()
tests/test_stage2.py 85 lines
"""Bug 2: drivers get deliveries after their shift has ended (see README)."""

import unittest

from delivery.dispatch import dispatch
from delivery.models import Delivery, Driver, Priority
from delivery.timeutil import TimeWindow, parse_window


def delivery(delivery_id, window, priority=Priority.NORMAL):
    return Delivery(delivery_id, "Ana Lopez", "central", parse_window(window), priority)


def driver(name, shift, *standing):
    return Driver(name, parse_window(shift), stops=list(standing))


def ids(deliveries):
    return [d.id for d in deliveries]


class TestOverlaps(unittest.TestCase):
    def assert_overlap(self, a, b, expected):
        first, second = parse_window(a), parse_window(b)
        self.assertEqual(first.overlaps(second), expected, f"{a} vs {b}")
        self.assertEqual(second.overlaps(first), expected, f"{b} vs {a}")

    def test_back_to_back_windows_do_not_overlap(self):
        self.assert_overlap("6:00-11:00", "11:00-13:00", False)
        self.assert_overlap("9:00-10:00", "10:00-11:00", False)
        self.assert_overlap("13:00-19:00", "11:00-13:00", False)

    def test_sharing_a_single_minute_is_an_overlap(self):
        self.assert_overlap("6:00-11:01", "11:00-13:00", True)
        self.assert_overlap("9:00-10:00", "9:59-10:30", True)

    def test_partial_overlap_containment_and_identical(self):
        self.assert_overlap("6:00-11:00", "10:00-13:00", True)
        self.assert_overlap("6:00-11:00", "5:00-7:00", True)
        self.assert_overlap("6:00-18:00", "9:00-10:00", True)
        self.assert_overlap("9:00-10:00", "9:00-10:00", True)

    def test_minute_level_windows(self):
        self.assertTrue(TimeWindow(600, 601).overlaps(TimeWindow(600, 601)))
        self.assertFalse(TimeWindow(600, 601).overlaps(TimeWindow(601, 602)))


class TestShiftBoundaries(unittest.TestCase):
    def test_morning_driver_does_not_get_a_delivery_that_starts_as_they_finish(self):
        sam = driver("Sam", "6:00-11:00")
        result = dispatch([delivery("D1", "11:00-13:00")], [sam])
        self.assertEqual(ids(result.unassigned), ["D1"])
        self.assertEqual(sam.stops, [])

    def test_it_goes_to_the_driver_who_is_on_shift(self):
        sam = driver("Sam", "6:00-11:00")
        priya = driver("Priya", "11:00-17:00", delivery("S1", "11:00-11:30"), delivery("S2", "11:30-12:00"))
        result = dispatch([delivery("D1", "11:00-13:00")], [sam, priya])
        self.assertEqual(ids(result.assignments["Priya"]), ["D1"])
        self.assertEqual(result.assignments["Sam"], [])

    def test_afternoon_driver_does_not_get_a_delivery_that_ends_as_they_start(self):
        lee = driver("Lee", "13:00-19:00")
        result = dispatch([delivery("D1", "11:00-13:00")], [lee])
        self.assertEqual(ids(result.unassigned), ["D1"])

    def test_partial_overlap_with_a_shift_is_still_fine(self):
        sam = driver("Sam", "6:00-11:00")
        result = dispatch([delivery("D1", "10:00-12:00"), delivery("D2", "5:00-7:00"),
                           delivery("D3", "10:59-11:30")], [sam])
        self.assertEqual(ids(result.assignments["Sam"]), ["D2", "D1", "D3"])

    def test_a_full_day(self):
        early, late = driver("Early", "6:00-11:00"), driver("Late", "11:00-17:00")
        deliveries = [delivery("D1", "9:00-11:00"), delivery("D2", "11:00-12:00"),
                      delivery("D3", "10:00-11:00"), delivery("D4", "16:00-17:00"),
                      delivery("D5", "17:00-18:00", priority=Priority.HIGH)]
        result = dispatch(deliveries, [early, late])
        self.assertEqual(ids(result.assignments["Early"]), ["D1", "D3"])
        self.assertEqual(ids(result.assignments["Late"]), ["D2", "D4"])
        self.assertEqual(ids(result.unassigned), ["D5"])


if __name__ == "__main__":
    unittest.main()
tests/test_stage3.py 66 lines
"""Bug 3: drivers' route sheets show each other's deliveries (see README)."""

import unittest

from delivery.dispatch import build_roster, dispatch
from delivery.models import Delivery, Driver
from delivery.route import plan_route
from delivery.timeutil import parse_window

SHIFTS = {"Ana": "6:00-16:00", "Ben": "6:00-16:00", "Cy": "6:00-16:00"}


def delivery(delivery_id, window, zone="central"):
    return Delivery(delivery_id, f"Customer {delivery_id}", zone, parse_window(window))


def ids(deliveries):
    return [d.id for d in deliveries]


def todays_deliveries(prefix, count):
    return [delivery(f"{prefix}{n}", f"{7 + n}:00-{8 + n}:00") for n in range(count)]


class TestDriversKeepTheirOwnStops(unittest.TestCase):
    def test_new_drivers_start_with_empty_routes(self):
        shift = parse_window("6:00-16:00")
        ana, ben = Driver("Ana", shift), Driver("Ben", shift)
        ana.assign(delivery("D1", "9:00-10:00"))
        self.assertEqual(ids(ana.stops), ["D1"])
        self.assertEqual(ben.stops, [])
        self.assertEqual(Driver("Cy", shift).stops, [])

    def test_each_route_sheet_only_lists_that_drivers_deliveries(self):
        roster = build_roster(SHIFTS, max_stops=2)
        result = dispatch(todays_deliveries("D", 6), roster)
        self.assertEqual(result.unassigned, [])
        for driver in roster:
            with self.subTest(driver=driver.name):
                self.assertEqual(ids(driver.stops), ids(result.assignments[driver.name]))
                self.assertEqual(len(driver.stops), 2)
                self.assertEqual(ids(s.delivery for s in plan_route(driver)), ids(driver.stops))

    def test_rerunning_the_scheduler_starts_from_scratch(self):
        first_run = build_roster(SHIFTS)
        dispatch(todays_deliveries("A", 3), first_run)
        second_run = build_roster(SHIFTS)
        result = dispatch(todays_deliveries("B", 3), second_run)
        self.assertEqual({name: ids(ds) for name, ds in result.assignments.items()},
                         {"Ana": ["B0"], "Ben": ["B1"], "Cy": ["B2"]})
        self.assertEqual([ids(d.stops) for d in second_run], [["B0"], ["B1"], ["B2"]])
        self.assertEqual([ids(d.stops) for d in first_run], [["A0"], ["A1"], ["A2"]])

    def test_drivers_preloaded_from_the_same_standing_order_list(self):
        standing = [delivery("CAFE", "6:30-7:00", zone="east")]
        shift = parse_window("6:00-16:00")
        ana = Driver("Ana", shift, stops=standing)
        ben = Driver("Ben", shift, stops=standing)
        dispatch(todays_deliveries("D", 4), [ana, ben])
        self.assertEqual(ids(ana.stops), ["CAFE", "D0", "D2"])
        self.assertEqual(ids(ben.stops), ["CAFE", "D1", "D3"])
        self.assertEqual(ids(standing), ["CAFE"], "the caller's standing-order list must not change")


if __name__ == "__main__":
    unittest.main()
tests/test_stage4.py 78 lines
"""Bug 4: urgent deliveries aren't treated as urgent (see README)."""

import unittest

from delivery.dispatch import dispatch
from delivery.models import Delivery, Driver, Priority
from delivery.route import order_stops, plan_route
from delivery.timeutil import parse_window

URGENT, HIGH, NORMAL, LOW = Priority.URGENT, Priority.HIGH, Priority.NORMAL, Priority.LOW


def delivery(delivery_id, window, priority, zone="central"):
    return Delivery(delivery_id, f"Customer {delivery_id}", zone, parse_window(window), priority)


def driver(name, shift, *standing, max_stops=8):
    return Driver(name, parse_window(shift), max_stops, stops=list(standing))


def ids(deliveries):
    return [d.id for d in deliveries]


class TestRouteOrder(unittest.TestCase):
    STOPS = [
        delivery("D1", "9:00-11:00", LOW),
        delivery("D2", "9:00-11:00", NORMAL),
        delivery("D3", "9:00-11:00", URGENT),
        delivery("D4", "9:00-11:00", HIGH),
        delivery("D5", "8:00-9:00", LOW),
        delivery("D0", "9:00-11:00", URGENT),
        delivery("D6", "13:00-14:00", URGENT),
    ]

    def test_within_a_window_most_urgent_first(self):
        self.assertEqual(ids(order_stops(self.STOPS)), ["D5", "D0", "D3", "D4", "D2", "D1", "D6"])

    def test_every_pair_of_priorities(self):
        ranked = [URGENT, HIGH, NORMAL, LOW]
        for i, more in enumerate(ranked):
            for less in ranked[i + 1:]:
                with self.subTest(more=more.name, less=less.name):
                    pair = [delivery("A", "9:00-10:00", less), delivery("B", "9:00-10:00", more)]
                    self.assertEqual(ids(order_stops(pair)), ["B", "A"])

    def test_the_urgent_cake_gets_the_earliest_eta_in_its_window(self):
        sam = driver("Sam", "8:30-15:00", *self.STOPS[:4])
        stops = plan_route(sam)
        self.assertEqual([(s.delivery.id, s.eta) for s in stops],
                         [("D3", 540), ("D4", 560), ("D2", 580), ("D1", 600)])


class TestDispatchOrder(unittest.TestCase):
    def test_least_urgent_deliveries_wait_when_short_of_drivers(self):
        sam = driver("Sam", "6:00-15:00", max_stops=2)
        result = dispatch([delivery("D1", "9:00-11:00", LOW), delivery("D2", "9:00-11:00", NORMAL),
                           delivery("D3", "9:00-11:00", URGENT), delivery("D4", "9:00-11:00", HIGH)], [sam])
        self.assertEqual(ids(result.assignments["Sam"]), ["D3", "D4"])
        self.assertEqual(ids(result.unassigned), ["D2", "D1"])

    def test_priority_beats_an_earlier_window(self):
        sam = driver("Sam", "6:00-15:00", max_stops=1)
        result = dispatch([delivery("D1", "8:00-9:00", NORMAL), delivery("D2", "14:00-15:00", URGENT)], [sam])
        self.assertEqual(ids(sam.stops), ["D2"])

    def test_normal_before_low(self):
        ana = driver("Ana", "6:00-15:00", max_stops=1)
        ben = driver("Ben", "6:00-15:00", max_stops=1)
        result = dispatch([delivery("D1", "8:00-9:00", LOW), delivery("D2", "10:00-11:00", NORMAL),
                           delivery("D3", "9:00-10:00", NORMAL)], [ana, ben])
        self.assertEqual(ids(result.assignments["Ana"]), ["D3"])
        self.assertEqual(ids(result.assignments["Ben"]), ["D2"])
        self.assertEqual(ids(result.unassigned), ["D1"])


if __name__ == "__main__":
    unittest.main()

Download the starter repo. Done, or out of time? Download the reference solution (spoilers) and compare it with yours.

More AI coding interview practice

Reviewed by Stephen Cognetta, CEO of Aced. Last updated: December 4, 2026

. . .