250. Python Program to Book Train Tickets with a Waiting List
MediumPhase 2 · Practice
You know everything this one uses: a while loop, two lists and join(). It just takes a few steps.
Overview
Train and bus companies sell a fixed number of seats. When the seats run out, they keep a waiting list. If someone cancels, the first person on the waiting list gets the seat.
Problem Statement
Sofia sells tickets for a small train. The first line of the input is the number of seats on the train. After it, read one command per line until a line says end. The commands are:
book <name>: if a seat is free, the person gets it: print<name> got a seat. If all seats are taken, the person joins the end of the waiting list: print<name> is on the waiting list. If the person already has a seat or is already waiting, print<name> already has a booking.cancel <name>: if the person has a seat, they give it up: print<name> cancelled. Then, if anyone is waiting, the first person on the waiting list gets that seat: print<name> got a seatwith their name. If the person is on the waiting list instead, take them off it: print<name> left the waiting list. Otherwise, print<name> has no booking.show: print two lines,Seats: <names>andWaiting: <names>. Put a comma and a space between the names. List the seated people in the order they got their seats, and the waiting list from first to last. Printnonefor an empty list.
For any other command, print Unknown command. Names must match exactly.
Examples
Example 1. Input:
2
book Ali
book Bea
book Chen
book Dev
show
cancel Ali
show
end
gives:
Ali got a seat
Bea got a seat
Chen is on the waiting list
Dev is on the waiting list
Seats: Ali, Bea
Waiting: Chen, Dev
Ali cancelled
Chen got a seat
Seats: Bea, Chen
Waiting: Dev
Why: the train has 2 seats, so Chen and Dev must wait. When Ali cancels, Chen is first on the waiting list, so Chen gets the seat. Chen got the newest seat, so Chen comes after Bea.
Example 2. Input:
1
book Eva
book Eva
cancel Finn
book Finn
cancel Finn
cancel Eva
show
end
gives:
Eva got a seat
Eva already has a booking
Finn has no booking
Finn is on the waiting list
Finn left the waiting list
Eva cancelled
Seats: none
Waiting: none
Why: Eva cannot book twice. Finn has no booking at first, then waits, then leaves the waiting list. When Eva cancels, nobody is waiting, so the seat stays free.
Input
The first line is the number of seats, a whole number of 1 or more. Then one command per line, with one space between the command and the name. Names are one word. The last line is always end. Use input() with no prompt text: the tests type the input for you, and a prompt would end up in your output.
Output
One line for each book or unknown command, one or two lines for each cancel, and two lines for each show. The tests try 7 different inputs, also people who leave the waiting list and seats that pass down the list more than once.
Try it first. The solution opens when you solve this question, or after 3 tries with Submit.