Python 优先级队列

java PriorityQueue类在Java1.5中引入。PriorityQueue是基于优先堆的一个无界队列,这个优先队列中的元素可以默认自然排序或者通过提供的Comparator(比较器)在队列实例化的时排序。要求使用Java Comparable和Comparator接口给对象排序,并且在排序时会按照优先级处理其中的元素

python 优先级队列

这里按"值越大优先级越高"的顺序.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

#coding=utf-8

from heapq import heappush, heappop

class PriorityQueue:

  def __init__(self):

    self._queue = []

  

  def put(self, item, priority):

    heappush(self._queue, (-priority, item))

  

  def get(self):

    return heappop(self._queue)[-1]

  

q = PriorityQueue()

q.put('world', 1)

q.put('hello', 2)

print q.get()

print q.get()

使用heapq模块来实现
下面的类利用 heapq 模块实现了一个简单的优先级队列:

1

2

3

4

5

6

7

8

9

10

11

12

13

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]

下面是它的使用方式:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

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

Item('bar')

>>> q.pop()

Item('spam')

>>> q.pop()

Item('foo')

>>> q.pop()

Item('grok')

>>>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值