Python實戰從入門到精通第四講——數據結構與算法2之實現一個優先級隊列

實現一個優先級隊列

import heapq

class PriorityQueue:
    def __init__(self):
        self._queue = []
        self._index = ()
    
    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)


q = PriorityQueue()
q.push(Item('foo'),1)
q.push(Item('bar'),5)
q.push(Item('spam'),4)
q.push(Item('grok'),1)
q.pop()
q.pop()
q.pop()
q.pop()

######輸出
Item('bar')
Item('spam')
Item('foo')
Item('grok')

可以看到第一個pop返回優先級最高的元素。

在代碼中隊列包含了一個(-priority,index,item)的元組,優先級爲負數的目的是使得元素按照優先級從高到低排序,這個跟普通的按優先級從低到高排序的堆排序恰好相反。

發佈了367 篇原創文章 · 獲贊 188 · 訪問量 51萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章