Python cookbook (data structure and algorithm) method example for implementing priority queue, pythoncookbook

Source: Internet
Author: User

Python cookbook (data structure and algorithm) method example for implementing priority queue, pythoncookbook

This article describes how to implement priority queue in Python. We will share this with you for your reference. The details are as follows:

Problem:To implement a queue, it can sort the elements with the given priority, and the element with the highest priority will be returned for each pop operation;

Solution:Use the heapq module to implement a simple priority queue

# example.py## Example of a priority queueimport heapqclass 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]# Example useclass Item:  def __init__(self, name):    self.name = name  def __repr__(self):    return 'Item({!r})'.format(self.name)q = PriorityQueue()q.push(Item('foo'), 1)q.push(Item('bar'), 5)q.push(Item('spam'), 4)q.push(Item('grok'), 1)print("Should be bar:", q.pop())print("Should be spam:", q.pop())print("Should be foo:", q.pop())print("Should be grok:", q.pop())
Python 3.4.0 (v3.4.0:04f714765c13, Mar 16 2014, 19:24:06) [MSC v.1600 32 bit (Intel)] on win32Type "copyright", "credits" or "license()" for more information.>>> ================================ RESTART ================================>>> Should be bar: Item('bar')Should be spam: Item('spam')Should be foo: Item('foo')Should be grok: Item('grok')>>> 

It can be seen that the elements returned during the first pop () operation have the highest priority. The returned order of the two elements with the same priority (foo and gork) is the same as that of the elements inserted to the queue.

In this Code, the queue uses the-priority, self. _ index, item) format composition, priority takes negative values to queue in the order from high to low, which is opposite to the default heap from small to large.

The function of the variable index is to arrange elements with the same priority in an appropriate order, especially for comparison between elements with the same priority.

Order comparison cannot be performed for Item instances:

a=Item('foo')b=Item('bar')print('a<b: ',a<b)>>> Traceback (most recent call last): File "D:\4autotests\02script\python-cookbook\python-cookbook-master\src\1\5.implementing_a_priority_queue\example.py", line 27, in <module>  print('a<b: ',a<b)TypeError: unorderable types: Item() < Item()>>> 

If elements are expressed in the form of tuples (priority, item), you can compare them as long as their priorities are different:

a=(1,Item('foo'))b=(5,Item('bar'))c=(1,Item('gork'))print('a<b: ',a<b)print('a<c: ',a<c)>>> a<b: TrueTraceback (most recent call last): File "D:\4autotests\02script\python-cookbook\python-cookbook-master\src\1\5.implementing_a_priority_queue\example.py", line 29, in <module>  print('a<c: ',a<c)TypeError: unorderable types: Item() < Item()>>> 

The introduction of additional index values and the creation of tuples in the (priority, index, item) method can avoid the problem that the same priority cannot be compared, because no two tuples have the same index value;

a=(1,0,Item('foo'))b=(5,1,Item('bar'))c=(1,2,Item('gork'))print('a<b: ',a<b)print('a<c: ',a<c)>>> a<b: Truea<c: True>>>

If you want to use this queue for inter-thread communication, you also need to add an appropriate lock and signal mechanism.

(The code is from Python Cookbook.)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.