In: Computer Science
Assuming you are write a program for the emergency room. You
maintain two queues. A regular FIFO queue for doctors. When a
doctor walked in, he/she will join this queue if there is no
patients waiting.
Otherwise, remove the patient with the highest priority and let the
doctor treat this patient.
A priority queue for patients. When a patient walked, input
patients name and priority. If doctor’s queue is not empty, remove
the first doctor and let this doctor server this patients.
Otherwise add this patient with the priority to the priority
queue.
PYTHON
Code tested in Python 3.6.9 in the Linux operating system.
Idea
We will use 2 modules available in Python to solve this problem
Helpful and self-explanatory comments are added to the code and output is also attached.
Code
from collections import deque
from heapq import heappush, heappop
class Doctor:
  def __init__(self, id):
    self.id = id
class Patient:
  def __init__(self, name, priority):
    self.name = name
    self.priority = priority
  # Comparator method for priority queue
  def __lt__(self, other):
    if self.priority == other.priority:
      # If priority is same, take element with lexographically shorter name first
      return self.name <= other.name
    # Else, take element with higher priorty first
    return self.priority > other.priority
doctors_queue = deque()
waiting_list = [] # For patients
# Series of events
events = [
  Patient('John', 10), # (Patient Name, Priority)
  Patient('Wick', 20),
  Doctor(1), # (DoctorID)
  Doctor(2),
  Doctor(3),
  Doctor(4),
  Patient('Lorem', 2),
  Patient('Epsum', 1),
  Patient('EFD', 1),
  Patient('ABC', 1),
  Doctor(5),
]
# Process events
for e in events:
  # Check if a doctor arrived
  if isinstance(e, Doctor):
    print('Doctor {} arrived'.format(e.id))
    # Check if a patient is waiting
    if len(waiting_list) > 0:
      # Pop the highest priority patient from waiting list
      patient = heappop(waiting_list)
      print('Patient [{}] with priority = {} assigned to Doctor {}'.format(patient.name, patient.priority, e.id))
    else:
      # No patient waiting, join the queue
      doctors_queue.append(e)
      print('Doctor {} joined the queue'.format(e.id))
  else:
    print('Patient [{}] with priority = {} arrived'.format(e.name, e.priority))
    # Check if a doctor is available
    if len(doctors_queue) > 0:
      # If yes, assign patient to this doctor
      doctor = doctors_queue.popleft()
      print('Patient [{}] with priority = {} assigned to Doctor {}'.format(e.name, e.priority, doctor.id))
    else:
      # Otherwise, add patient to priority queue
      heappush(waiting_list, e)
      print('Patient [{}] joined the queue'.format(e.name))
Output
