码迷,mamicode.com
首页 > 编程语言 > 详细

python Cookbook

时间:2019-05-16 20:26:53      阅读:146      评论:0      收藏:0      [点我收藏+]

标签:ret   优先   index   for   format   item   span   一个   pre   

1.5 heapq模块实现一个优先级队列

#实现优先级队列
import heapq
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]

    def __get__(self):#get(),set()
        return self._queue

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(grop),1)

q.pop()#bar
q.pop()#spam
q.pop()#foo
print(q.__get__())

 

python Cookbook

标签:ret   优先   index   for   format   item   span   一个   pre   

原文地址:https://www.cnblogs.com/heyaqiong/p/10877699.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!