Design a Booking System
Lesson 48 of 48 in Coddy's Python for Rust Developers course.
Challenge
BeginnerDesign a complete booking program with two collaborating objects: a Room that owns capacity and reservations, and a BookingDesk that validates commands and uses that room. Implement Room(capacity) with instance attributes capacity and bookings (a name-to-seat-count dictionary), plus methods reserve(name, seats) and cancel(name) that raise ValueError on rejection. Implement BookingDesk(room) storing room, with handle(command) returning ok or invalid. It must delegate validly shaped commands to the current room, catch ValueError, and not print. The complete program handles input and printing. Input is a nonnegative integer capacity, a nonnegative command count, then that many command lines. A command is reserve name seats or cancel name. Names are nonempty lowercase ASCII tokens. Reservation seats must parse as an integer and be positive, the name must not already hold a reservation, and enough seats must remain. A cancellation requires an existing name. Reject bad integer text, unknown operations, wrong field counts, empty commands, and all failed business rules. Print ok or invalid for every command. Rejection changes nothing. After all commands print available:N, then each active name:seats in ascending name order. Canceled names can book again. A zero-capacity room accepts no reservations. Use only in-memory data; no actual booking service is contacted.
A locked driver also creates independent rooms, checks rejected operations preserve state, and replaces the desk's room with a probe to verify calls to reserve and cancel. It prints nothing and reads no additional input.
Edit room.py for Room, booking_desk.py for BookingDesk, and main.py for input and printing inside main(). Keep the supplied imports and entry-point wrapper. The desk uses the room object passed to its constructor; it does not create or import a second room. The locked driver.py calls main() once and then runs the supplied API checks without reading more input.
Try it yourself
from room import Room
from booking_desk import BookingDesk
from main import main
main()
probe_room = Room(4)
other_room = Room(4)
probe_room.reserve("a", 3)
assert probe_room.capacity == 4 and probe_room.bookings == {"a": 3}
assert other_room.bookings == {}
for name, seats in [("a", 1), ("b", 2), ("c", 0), ("d", -1)]:
try:
probe_room.reserve(name, seats)
except ValueError:
pass
else:
raise AssertionError("Invalid reservation accepted")
assert probe_room.bookings == {"a": 3}
try:
probe_room.cancel("missing")
except ValueError:
pass
else:
raise AssertionError("Unknown cancellation accepted")
probe_room.cancel("a")
assert probe_room.bookings == {}
probe_desk = BookingDesk(other_room)
assert probe_desk.room is other_room
assert probe_desk.handle("reserve x 4") == "ok"
assert other_room.bookings == {"x": 4}
class ProbeRoom:
def __init__(self):
self.calls = []
def reserve(self, name, seats):
self.calls.append(("reserve", name, seats))
if seats == 9:
raise ValueError("probe rejection")
def cancel(self, name):
self.calls.append(("cancel", name))
probe = ProbeRoom()
probe_desk.room = probe
assert probe_desk.handle("reserve y 2") == "ok"
assert probe_desk.handle("cancel y") == "ok"
assert probe_desk.handle("reserve z 9") == "invalid"
assert probe_desk.handle("reserve a bad") == "invalid"
assert probe.calls == [("reserve", "y", 2), ("cancel", "y"), ("reserve", "z", 9)]
All lessons in Python for Rust Developers
1From Rust to Python
Run Your First Python ProgramMacros to printBindings, mut, and ShadowingIntegers and Floor DivisionIndentation and ScopeRecap: Rewrite a Receipt4Iteration and Transformations
Borrowed Iteration to forEntries and enumeratewhile, break, and continueIterators and ComprehensionsRecap: Build a Ranking2Values and Decisions
Option and NoneEquality and Object IdentityTruth Tests and FallbacksIf Expressions and elifRecap: Eligibility Rules3Ownership and Collections
Vec to listTuples and DestructuringHashMap to dictClone and Shallow CopiesRecap: Clean an Inventory6Errors and Modules
Text Input and FormattingResult, Exceptions, and withModules and the Main GuardHints Without Borrow CheckingRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler