Design priority queue in python from basic
In this session, we are going to learn what is priority queue and how can we implement in an easy way using python programming.
what do you mean by a priority queue
The priority queue is a set of the elements in which elements can be added at any time, but the only element that can be removed is the one with the highest priority.
now we are going to jump in the program.so 1st take the class and within that, we have to declare four functions
which handle all operation of the priority queue.
1) def __init__(self)
—>for initialization of queue.
2) def isEmpty(self)
—>for checking queue is empty or not.
3) def insert(self, data)
—>for inserting the element into the queue
4) def popout(self)
—->for deleting the element of the highest priority.
now the whole code of Python Priority queue is:
#Priority Queue implementation using Queue concepts. class P_Queue(object): def __init__(self): self.q =  #In built function isEmpty to checking if the queue is empty def isEmpty(self): return len(self.q)== #In built function for inserting an element in the queue def insert(self, data): self.q.append(data) #delete function for popout an element based on theirPriority def popout(self): try: #initialization of variable. max=0 #for loop for finding maximum value in the queue. for i in range(len(self.q)): if self.q[i] > self.q[max]: max = i #store maximum value element in x. x=self.q[max] #del function use to delete the maximum value from queue. del self.q[max] #return max value return x except IndexError: print() exit() # class object ob=P_Queue() #taking queue size from users x=int(input("Enter the size of queue")) #for loop to insert the element into he queue by calling insert function. for i in range(x): ob.insert(int(input("Enter the element "))) #print element according to their priority while not ob.isEmpty(): print(ob.popout())
Enter the size of queue5 Enter the element 23 Enter the element 6 Enter the element 41 Enter the element 12 Enter the element 56 56 41 23 12 6