AlgoViz

Design a parking lot

medium 90 min

Model a car park with several levels as classes: vehicles, spaces of different sizes, tickets and a replaceable price rule.

Watch lesson4:48

Payment and lost tickets

Exactly one charge, whatever breaks

The point: every step at the exit may be repeated and the result must not change. Fix the price once, use one key per bill, and let the status say what is done.

States

Pay first, drive later

The session of one stay

In time means within 15 minutes of paying. The barrier looks only at Paid and the time. It never calculates.
Python
from dataclasses import dataclassfrom datetime import datetime, timedelta, timezonefrom enum import Enumclass Status(Enum):    ACTIVE = "active"    PAID = "paid"    LEFT = "left"    LOST = "lost"@dataclassclass Session:    ticket_id: str    entered_at: datetime    status: Status = Status.ACTIVE    quoted_cents: int | None = None    paid_until: datetime | None = Noneclass Bank:    """Answers the same for the same key, however often it is asked."""    def __init__(self) -> None:        self.charges: dict[str, int] = {}    def charge(self, key: str, cents: int) -> None:        if self.charges.setdefault(key, cents) != cents:            raise ValueError("same key, other amount")class ExitDesk:    def __init__(self, bank: Bank, now) -> None:        self._bank, self._now = bank, now    def quote(self, s: Session) -> int:        if s.quoted_cents is None:                  # write the price down once            seconds = int((self._now() - s.entered_at).total_seconds())            s.quoted_cents = max(1, (seconds + 3599) // 3600) * 200        return s.quoted_cents    def pay(self, s: Session) -> None:        if s.status is Status.ACTIVE:            self._bank.charge(f"{s.ticket_id}:1", self.quote(s))            s.status = Status.PAID            s.paid_until = self._now() + timedelta(minutes=15)    def open_gate(self, s: Session) -> bool:        if s.status is Status.LEFT:            return True                             # asked twice: same answer        if s.status is not Status.PAID or self._now() > s.paid_until:            return False        s.status = Status.LEFT        return Truetime = [datetime(2026, 7, 4, 9, tzinfo=timezone.utc)]bank = Bank()desk = ExitDesk(bank, lambda: time[0])session = Session("T7", time[0])time[0] += timedelta(minutes=130)desk.pay(session)desk.pay(session)                                   # the customer pressed twiceprint(bank.charges, desk.open_gate(session), desk.open_gate(session))
Pressing twice charges once, twice over: the status stops the second call, and if the status was lost the key stops the second charge. open_gate answers the same when asked again.
Edit and run it in your browser

Key

Why the price must be written down first

A retry with the same key must carry the same amount. If the price is calculated again on the retry and a new hour has begun, the amount differs. A payment provider may refuse that, or return the first result, and your receipt then says something else than the bank. So: quote, store, charge what is stored.

KeyProblem
A new random key for each tryEvery retry is a new charge. This is the mistake people make while believing they are safe
The ticket id aloneThe second payment (overstay) is swallowed by the first
Ticket id plus the number of the bill: T7:1, T7:2Right: a retry has the same number, a new bill has a new one
More on keys: idempotency.

Failure walk

Stop it at every line

It breaksMoneySpaceWhat happens next
Before the chargeNoTakenStatus still active or quoted. The driver tries again
Card declinedNoTakenSame ticket, another card, same bill
Timeout: charged or not?UnknownTakenAsk again with the same key and the same amount. Never with a new one
Charged, then we crash before saving PaidYesTakenOn restart, sessions with a stored price and no result are asked again with their key: the answer is charged
Paid, barrier motor stuckYesTaken until the car passesOpen by hand. open_gate again gives yes
Left saved, release lostYesTaken by nobodyA check every night: spaces on sessions that have left are released
Two exits, same ticketOnceOnceThe first changes Paid to Left. At the second the car is recognised as a copy, if its plate differs
Release must happen, but not with a finally that also runs when the payment failed. It hangs on the status.

Lost

Lost tickets

Python
def lost_ticket_cents(found_fee: int | None, daily_max: int = 5000, admin: int = 2000) -> int:    """Entry found by plate: the real fee plus handling. Not found: one full day plus handling."""    return (found_fee if found_fee is not None else daily_max) + adminprint(lost_ticket_cents(600), lost_ticket_cents(None))
With the plate from the camera the entry time is known: the real fee plus handling, 600 + 2000 = 2600. Without: one full day plus handling, 5000 + 2000 = 7000 cents.
Edit and run it in your browser
  1. 1

    Find it

    By plate, then by space: "I stand in M1". Both indexes exist.

  2. 2

    Check the person

    Plates are public. The desk looks at the papers or the key. A system that opens for a spoken plate helps car thieves.

  3. 3

    Close the old ticket

    Status Lost. If the paper turns up in another hand, it opens nothing.

  4. 4

    Charge once

    The lost fee is a new bill with its own number, and refundable if the ticket is found.

When do you release the space?

BreaksFirst
How
Release, then price, then charge.
Limit
The next car is sent to a space with a car in it, or the driver never pays.
Choose when
Never.
WorksAfter the charge
How
As in the base code: pay at the barrier, the car has already left its space.
Limit
With machines at the doors the car is still parked for 15 minutes.
Choose when
Payment at the exit barrier.
StrongWhen the car passes the exit
How
Paid opens the barrier, the sensor behind it sets Left and releases.
Limit
A missed sensor keeps a space. The nightly check finds it.
Choose when
Pay first and drive later.

Methods

Cash, card, phone

Each method implements Payments. Cash answers at once, a card within seconds, a phone payment perhaps after a minute through a message. So the contract is: start a payment with a key, and later learn the result: pending, completed, failed, refunded. The session waits with its stored price. No lock waits with it.