Python cookbook(資料結構與演算法)實現優先順序隊列的方法樣本,pythoncookbook

來源:互聯網
上載者:User

Python cookbook(資料結構與演算法)實現優先順序隊列的方法樣本,pythoncookbook

本文執行個體講述了Python實現優先順序隊列的方法。分享給大家供大家參考,具體如下:

問題:要實現一個隊列,它能夠以給定的優先順序對元素排序,且每次pop操作時都會返回優先順序最高的那個元素;

解決方案:採用heapq模組實現一個簡單的優先順序隊列

# 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')>>> 

可以看出:第一次執行pop()操作時返回的元素具有最高的優先順序;對於相同優先順序的兩個元素(foo和gork)返回的順序同它們插入到隊列時的順序相同。

在這段代碼中,隊列以元組(-priority, self._index, item)的形式組成,priority取負值是為了隊列按照從高到低的順序排列,這和堆預設的從小到大的排序相反。

變數index的作用是對相同優先順序的元素以適當的順序排列,特別對同優先順序的元素間做比較操作時扮演了重要的角色。

Item執行個體無法進行次序比較:

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()>>> 

如果以元組(priority,  item)的形式來表示元素,只要優先順序不同,就可進行比較:

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()>>> 

引入額外的索引值,以(priority, index, item)的方式建立元組,就可以避免相同優先順序無法比較的問題,因為沒有哪兩個元組會有相同的index值;

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>>>

如果想將這個隊列用於線程間通訊,還需要增加適當的鎖和訊號機制。

(代碼摘自《Python Cookbook》)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.