Python Tutorial: Priority Queue Comparator

Develop a custom priority queue in Python.

Priority Queue in Python

A priority queue is a data structure that allows us to store items with a certain priority. The priority queue will then order these items so that the item with the highest priority is at the top of the queue.

Priority queues are often used in algorithms where we need to process items in priority order. Let's say we're working on a task list; we want to tackle the most important tasks first.

We can implement it with a priority queue.

Priority Queue Custom Comparator

The built-in module queue in Python provides an implementation of a priority queue. However, this module does not allow us to specify a custom comparator for the priority queue.

This can be a problem if we want to use a different ordering for the priority queue than the default.

Fortunately, there is a way to create a custom comparator for a Python priority queue. In this article, we'll see how to do that.

We'll explore two examples of priority queues.

  • Priority queue using lists in Python
  • A priority queue using Python's heapdict module

priority queue using lists

First, we'll make a blank list. Afterwards, we'll add each person's name to the list in order of importance.

We'll start at 1 and work our way up. Therefore, each name will be assigned a number as a priority in the list.

The priority is an integer that determines the order in which tasks will be executed when they eventually complete.

Let's do it through code. First, we'll create a list called names.

This list will initially be empty. See code below.

names = []

Now, to add names to the list, we'll use the append method, which is readily available from the list function. The append method takes two parameters.

Add a number to the list for priority, number, name or something. For our purposes, we want the name Abid to appear at position1 in the list.

names.append((1, "Abid"))

There is no limit to the number of names or items that can be added, and the index numbers will indicate their priority.

Sample code:

names.append((1, "Abid"))
names.append((4, "Jesica"))
names.sort(reverse = True)
names.append((3, "Anna"))
names.sort(reverse = True)
names.append((2, "Pat"))

When we use the while loop here, the names list records will be printed.

while names:
    print(names.pop())

This is the same code that was created earlier, copy it and execute it to see the result.

names = []
names.append((1, "Abid"))
names.append((4, "Jesica"))
names.sort(reverse = True)
names.append((3, "Anna"))
names.sort(reverse = True)
names.append((2, "Pat"))
names.sort(reverse = True)
while names:
    print(names.pop())

output:

(1, 'Abid')
(2, 'Pat')
(3, 'Anna')
(4, 'Jesica')

Here is the output of running that code. We can clearly see that each name is sorted according to the priority and index we provided.

Priority queue using the heapdict module

Heap-based priority queues are implemented through the heapdict Python module. It is comparable to the normal heapq module, but offers more functionality and flexibility.

The binary heap is the basis of the heapdict data structure. A binary heap is a data structure that can be used to store data in a manner that facilitates efficient retrieval and alteration of that data.

A binary heap is a complete binary tree, which means that every node on the tree has two children, and the tree itself is always balanced.

HeapDict and are the two main classes provided by the module. The class functions like a dictionary and keeps its contents in a heap.

HeapQueue heapdict heapdict

The heap is used to hold information managed by a queue class called HeapQueue. The HeapDict and HeapQueue classes are built-in subclasses of the dict class.

They assume all the methods of dict and provide methods for interacting with the heap, which they inherit.

Note that the heapdict module is not automatically installed for us. We have to configure the heapdict using the command below.

pip install heapdict

Having finished installing the heapdict library, we are now ready to use it in our priority queue implementation.

  • The first step is to import the heapdict library.
  • Make a variable that calls the heapdict function and continue to use that variable for priority.
  • At this point, we'll use the function we developed earlier to assign a priority to each task.
  • Use a while loop.
  • Display the result by printing the variable.

The entire code can be written in the following form.

import heapdict
tasks = heapdict.heapdict()
tasks['Breakfast'] = 3
tasks['Wake up'] = 1
tasks['Get ready for work'] = 4
tasks['Exercise'] = 2
while tasks:
	print(tasks.popitem())
#Python小白学习交流群:153708845

output:

('Wake up', 1)
('Exercise', 2)
('Breakfast', 3)
('Get ready for work', 4)

The output of the code shows that the code runs correctly according to the order of priority assigned to the various tasks in the code. The output of our activity follows the same order and indicates the appropriate priority.

This article tells us how to use lists to build a priority queue. Besides that, we also went through the necessary steps to create a custom priority queue in Python.

We now know how to implement a custom comparator function with a priority queue.

We hope this article helped you understand how to create a custom priority queue in Python.

Guess you like

Origin blog.csdn.net/qdPython/article/details/132149106