Program to implement seat reservation manager in Python


Suppose we have to design a system that manages the reservation state of n seats. The seats are numbered from 1 to n. So we have to implement the SeatReserveManager class, with these functions −

  • Constructor that takes n as input and initializes the object that will manage n seats numbered from 1 to n. Initially all seats are available.

  • reserve(), this will fetch the smallest-numbered unreserved seat, then reserves it, and returns its number.

  • unreserve(seatNumber), this will unreserve one reserved seat with the given seatNumber.

So, if the input is like

  • obj = SeatReserveManager(7)

  • obj.reserve()

  • obj.reserve()

  • obj.reserve()

  • obj.unreserve(2)

  • obj.unreserve(5)

  • obj.reserve()

  • obj.reserve()

then the output will be 1, 2, 3, 2, 5, initially reserve three seats 1, 2, 3, then unreserved 2 and 5 but 5 is not reserved yet, then reserve 5 next.

To solve this, we will follow these steps −

  • Define the Constuctor() . This will take n

  • current_seat := 0

  • empty_seats := a new list

  • Define a function reserve() . This will take

  • if length of empty_seats > 0, then

    • s := minimum of empty_seats

    • delete s from empty_seats

    • return s

  • current_seat := current_seat + 1

  • return current_seat

  • Define a function unreserve(). This will take seatNumber

  • insert seatNumber at the end of empty_seats

Example

Let us see the following implementation to get better understanding −

class SeatReserveManager:
   def __init__(self, n):
      self.current_seat = 0
      self.empty_seats = []

   def reserve(self):
      if len(self.empty_seats) > 0:
         s = min(self.empty_seats)
         self.empty_seats.remove(s)
         return s
      self.current_seat += 1

      return self.current_seat

   def unreserve(self, seatNumber):
      self.empty_seats.append(seatNumber)

obj = SeatReserveManager(7)
print(obj.reserve())
print(obj.reserve())
print(obj.reserve())
obj.unreserve(2)
obj.unreserve(5)
print(obj.reserve())
print(obj.reserve())

Input

obj = SeatReserveManager(7)
print(obj.reserve())
print(obj.reserve())
print(obj.reserve())
obj.unreserve(2)
obj.unreserve(5)
print(obj.reserve())
print(obj.reserve())

Output

1 2 3 2 5

Updated on: 08-Oct-2021

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements