Implement a Python program that manages a train reservation system, raising custom exceptions for scenarios like train full, invalid station name, etc.
Example 1:
Input: Trains: {"train1": {"stations": ["station1", "station2", "station3"], "capacity": 100, "passengers": 50}}, Train: "train1", Station: "station2" Output: "Reservation successful."
Example 2:
Input: Trains: {"train1": {"stations": ["station1", "station2", "station3"], "capacity": 100, "passengers": 100}}, Train: "train1", Station: "station2" Output: "Error: Train full."
Use a dictionary to store the trains and their information.
def make_reservation(trains, train, station): if train not in trains: raise Exception("Error: Train not found.") elif station not in trains[train]["stations"]: raise Exception("Error: Invalid station name.") elif trains[train]["passengers"] >= trains[train]["capacity"]: raise Exception("Error: Train full.") else: trains[train]["passengers"] += 1 return "Reservation successful." trains = {"train1": {"stations": ["station1", "station2", "station3"], "capacity": 100, "passengers": 50}} print(make_reservation(trains, "train1", "station2")) # Output: "Reservation successful." print(make_reservation(trains, "train1", "station4")) # Output: "Error: Invalid station name."
Unlock AI & Data Science treasures. Log in!