Final: Booking System
Lesson 48 of 48 in Coddy's Python for C# Developers course.
Challenge
BeginnerBuild two cooperating objects and the program entry point. Room(capacity) owns capacity and a fresh bookings dictionary mapping names to seat counts. Its reserve(name, seats) and cancel(name) methods raise ValueError on rejection. BookingDesk(room) stores the supplied room; handle(command) returns ok or invalid, delegates well-shaped commands to the current room, catches ValueError, and never prints. Input is a nonnegative capacity, a nonnegative command count, and that many lines. Commands are reserve name seats or cancel name; names are nonempty lowercase ASCII tokens. Reservations require int-parsable positive seats, a new name, and enough space. Cancellation requires an existing name. Reject malformed integers, unknown operations, wrong field counts, empty commands, or failed business rules without changing state. main() prints a status per command, then available:N and active name:seats lines sorted by name. Canceled names can reserve again. Zero capacity accepts no reservations. Silent driver probes check independent rooms, unchanged state after rejection, and delegation to a replacement room. All data is in memory.
C# transfer checkpoint
A C# interface can declare the room contract. In Python, delegation to the supplied object allows the driver to substitute a compatible room; no inheritance check is needed.
C# reference excerpt: executable statements assume using System; type-only excerpts illustrate the declared contract.
interface IRoom { void Reserve(string name, int seats); void Cancel(string name); }Python pattern
class Desk:
def __init__(self, room):
self.room = room
def cancel(self, name):
return self.room.cancel(name)Editable implementation files: room.py, booking_desk.py, main.py. The locked driver.py is the supplied launcher or input/output harness and must remain unchanged.
Use the supplied input contract without prompts. Print only the required lines, each ending in a newline.
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 C# Developers
1C# Foundations in Python
Run the Python WorkspaceOutput, Strings, and CommentsTyped Locals to Python NamesDivision and RemaindersIndentation Instead of BracesRecap: Port a Receipt4Loops and Transformations
From foreach to forIndexes and Dictionary ItemsSentinels and Loop ControlFrom LINQ to ComprehensionsRecap: Stable Ranking2None and Decisions
Nullable Values and NoneEquality, Identity, and TypesTruth Tests and FallbacksBranch PriorityRecap: Eligibility Rules3Collections and References
From List<T> to listTuples and UnpackingDictionary Keys and ValuesSets, Aliases, and CopiesRecap: Stock Lookup6Reliable Python Programs
Input and Exact OutputExceptions and ValidationImports and the Main GuardType Hints and Runtime TypesRecap: Validate a Batch9Project: Order Processor
Project 1: Order ModelProject 2: Pricing PoliciesPractice on your own: Online Python compiler