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