-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpriority_queue.py
55 lines (44 loc) · 1.21 KB
/
priority_queue.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
'''
File: priority_queue.py
Project: DataSturcture
===========
File Created: Monday, 20th July 2020 12:01:48 pm
Author: <<LanLing>> (<<[email protected]>>)
===========
Last Modified: Monday, 20th July 2020 12:03:08 pm
Modified By: <<LanLing>> (<<[email protected]>>>)
===========
Description: 实现优先级队列
Copyright <<2020>> - 2020 Your Company, <<XDU>>
'''
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):
# 返回最小的元素,-1 表示取出 item
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()
a = Item('aoo')
b = Item('boo')
c = Item('coo')
q.push(a, 1)
q.push(b, 2)
q.push(c, 1)
# a 的索引小于 c,所以先弹出 a
print(q.pop())
print(q.pop())
print(q.pop())