Priority queue in Python
In this post, you will learn how to implement a Priority Queue using the Python programming language.
The priority of the element is used to determine the order in which the elements will be processed. The elements in the priority queue have some priority. In this element, it is inserted and deleted based on its priority.
The basic examples of Priority Queue-
- Operating System Scheduler
- Dijkstra's Shortest Path Algorithm
- Huffman Coding
These are the rules for processing elements in a priority queue.
- The element with the highest priority is processed first.
- The two elements with equal priority are processed based on a First Come First Serve(FCFS) basis.
The priority of the elements is set based on several factors. This is basically used in the operating system to execute the most priority process first. If this is set on the CPU time, then the element with the lowest execution time is executed first. Suppose there are two processes in a queue, one has 5ns execution time and the other has 10ns execution time, then the process having 5ns executes first.
Priority queue program using Python
Output of the above code:
class PriorityQueue(object): def __init__(self): self.queue =  def __str__(self): return ' '.join([str(i) for i in self.queue]) # check if the queue is empty def isEmpty(self): return len(self.queue) == 0 # inserting an element in the queue def insert(self, data): self.queue.append(data) # popping an element based on Priority def delete(self): try: max_val = 0 for i in range(len(self.queue)): if self.queue[i] > self.queue[max_val]: max_val = i item = self.queue[max_val] del self.queue[max_val] return item except IndexError: print() exit() if __name__ == '__main__': pQueue = PriorityQueue() print("Priority Queue: ") pQueue.insert(45) pQueue.insert(29) pQueue.insert(19) pQueue.insert(97) print(pQueue) while not pQueue.isEmpty(): print(pQueue.delete())
Priority Queue: 45 29 19 97 97 45 29 19
Related ArticlesConvert Python list to numpy array
Convert string to list Python
Python program to list even and odd numbers of a list
Python loop through list
Sort list in descending order Python
Convert array to list Python
Python take screenshot of specific window
Web scraping Python BeautifulSoup
Check if two strings are anagrams Python
Python program to add two numbers
Print new line python
Python for loop index
Convert List to Dataframe Python
numpy random choice
Dictionary inside list python
Check if list is empty Python
Python raise keyword
Python program to get the largest number from a list
Python program to map two lists into a dictionary