Python Utilities Part 4: Implementing Priority Queues

Keywords: Python

1. Requirements

We want to implement a queue that sorts elements at a given priority and returns the element with the highest priority each pop operation

2. Solutions (viii)

Implementation using heapq module

Code:

import heapq

#Implement a priority queue with heapq for short answers
class PriorityQueue:
    def __init__(self):
        self._queue=[]
        self._index=0
    def push(self,item,priority):
        heapq.heappush(self._queue,(-priority,self._index,item))
        self._index+=1
    def pop(self):
        return heapq.heappop(self._queue)[-1]

class Item:
    def __init__(self,name):
        self.name=name

    def __repr__(self):
        return 'Item({!r})'.format(self.name)

if __name__ == '__main__':
    q=PriorityQueue()
    q.push(Item('foo'),1)
    q.push(Item('bar'),5)
    q.push(Item('spam'),4)
    q.push(Item('grok'),1)

    print(q.pop())
    print(q.pop())
    #Two elements with the same priority are returned in the same order as they were inserted into the queue
    print(q.pop())
    print(q.pop())

Run result:

Item('bar')
Item('spam')
Item('foo')
Item('grok')
Python Resource Sharing qun 784758214 ,Installation packages are included. PDF,Learn video, here is Python The place where learners gather, zero base, advanced, all welcome

The core of the above code is the use of the heapq module.The functions heapq.heapqpush() and heapq.heapqpop() insert and remove elements from the list_queue, respectively, with the lowest priority for the first element in the list.The heappop() method always returns the [smallest] element, so this is the key to getting the queue to pop up the correct element.In addition, since both push and pop operations are O(logN) in complexity, where N represents the number of elements in the heap, these operations are very efficient even if N values are large.

In the code above, the queue is made up of tuples (-priority, index, item).Negative priority values are used to enable queues to be ordered from the highest priority to the lowest priority of elements.

The purpose of the variable index is to arrange elements of the same priority in the appropriate order.By maintaining an increasing index, elements are arranged in the order they appear as queues.To illustrate the role of index, see the following example:

Code:

class Item:
    def __init__(self,name):
        self.name=name

    def __repr__(self):
        return 'Item({!r})'.format(self.name)

if __name__ == '__main__':
    a=(1,Item('foo'))
    b=(5,Item('bar'))
    #Next sentence Print True
    print(a<b)

    c=(1,Item('grok'))
    #TypeError:'<'not supported between instances of'Item' and'Item'
    print(c<a)

    d=(1,0,Item('foo'))
    e=(5,1,Item('bar'))
    f=(1,2,Item('grok'))
    #Next sentence Print True
    print(d<e)
    #Next sentence Print True
    print(d<f)

Posted by rinteractive on Tue, 30 Jul 2019 09:37:15 -0700