Created
October 3, 2017 02:26
-
-
Save clarksun/ad5d3dea5d3868d9e066c3a594a74961 to your computer and use it in GitHub Desktop.
优先级队列 #heapq
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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'), 4) | |
# q.push(Item('grok'), 1) | |
# | |
# q.pop() # Item('bar') | |
# q.pop() # Item('spam') | |
# q.pop() # Item('foo') | |
# q.pop() # Item('grok') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment