Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Priority queue with higher priority first in Python

I need a priority queue that gets the item with the highest priority value first. I'm currently using the PriorityQueue Class from the Queue library. However, this function only returns the items with the lowest value first. I tried some ugly solutions like (sys.maxint - priority) as the priority, but was just wondering if a more elegant solution exists.

like image 565
Ashok Avatar asked Feb 27 '13 22:02

Ashok


People also ask

How do you sort a priority queue in Python?

In Python Priority Queue, a custom comparator can be used to sort the queue based on user-defined values. For example, we create a Priority Queue using heapq. Then we sort the heapq using the sorted() method. Now let us sort our queue based on our custom comparator.

Which element is processed first in priority queue?

How is Priority assigned to the elements in a Priority Queue? In a priority queue, generally, the value of an element is considered for assigning the priority. For example, the element with the highest value is assigned the highest priority and the element with the lowest value is assigned the lowest priority.

Does Python have inbuilt priority queue?

Python provides a built-in implementation of the priority queue data structure. Since the queue. PriorityQueue class needs to maintain the order of its elements, a sorting mechanism is required every time a new element is enqueued. Python solves this by using a binary heap to implement the priority queue.


2 Answers

Use a negative priority instead, no need to subtract from sys.maxint.

queue.put((-priority, item))

An item with priority -10 will be returned before items with priority -5, for example.

like image 159
Martijn Pieters Avatar answered Sep 28 '22 05:09

Martijn Pieters


You can extend the Priority Queue to keep the logic unchanged:

from Queue import PriorityQueue

class DualPriorityQueue(PriorityQueue):
    def __init__(self, maxPQ=False):
        PriorityQueue.__init__(self)
        self.reverse = -1 if maxPQ else 1

    def put(self, priority, data):
        PriorityQueue.put(self, (self.reverse * priority, data))

    def get(self, *args, **kwargs):
        priority, data = PriorityQueue.get(self, *args, **kwargs)
        return self.reverse * priority, data


minQ = DualPriorityQueue()
maxQ = DualPriorityQueue(maxPQ=True)

minQ.put(10, 'A')
minQ.put(100, 'A')


maxQ.put(10, 'A')
maxQ.put(100,'A')

print "Min DQ: {}".format(minQ.get())
print "Max DQ: {}".format(maxQ.get())

Output:

Min DQ: (10, 'A')
Max DQ: (100, 'A')
like image 34
anask Avatar answered Sep 28 '22 05:09

anask