码迷,mamicode.com
首页 > 其他好文 > 详细

[PY3]——实现一个优先级队列

时间:2017-07-10 16:34:35      阅读:207      评论:0      收藏:0      [点我收藏+]

标签:python   book   ini   for   form   tar   style   bsp   队列   

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]

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),2)
q.push(Item(grok),1)

print(q.pop())
print(q.pop())
print(q.pop())
print(q.pop())

   Item(bar)
   Item(spam)
   Item(foo)
   Item(grok)

 

参考文章

cookbook-python3-1.5-实现一个优先级队列

浅谈算法和数据结构: 五 优先级队列与堆排序

heap模块和堆排序

[PY3]——实现一个优先级队列

标签:python   book   ini   for   form   tar   style   bsp   队列   

原文地址:http://www.cnblogs.com/snsdzjlz320/p/7145820.html

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