File tree Expand file tree Collapse file tree 1 file changed +5
-5
lines changed Expand file tree Collapse file tree 1 file changed +5
-5
lines changed Original file line number Diff line number Diff line change 1
1
# 优先级队列
2
2
你可能比较奇怪,队列不是早就讲了嘛。这里之所以放到这里讲优先级队列,是因为虽然名字有队列,
3
- 其实使用的是堆来实现的 。上一章讲完了堆,这一章我们就来实现一个优先级队列 。
3
+ 但其实是使用堆来实现的 。上一章讲完了堆,这一章我们就趁热打铁来实现一个优先级队列 。
4
4
5
5
6
6
# 实现优先级队列
11
11
def test_priority_queue ():
12
12
size = 5
13
13
pq = PriorityQueue(size)
14
- pq.push(5 , ' purple' )
14
+ pq.push(5 , ' purple' ) # priority, value
15
15
pq.push(0 , ' white' )
16
16
pq.push(3 , ' orange' )
17
17
pq.push(1 , ' black' )
@@ -22,7 +22,7 @@ def test_priority_queue():
22
22
assert res == [' purple' , ' orange' , ' black' , ' white' ]
23
23
```
24
24
25
- 上边就是期望的行为,然后编写优先级队列,按照出队的时候最大优先级先出对的顺序 :
25
+ 上边就是期望的行为,写完测试代码后我们来编写优先级队列的代码,按照出队的时候最大优先级先出的顺序 :
26
26
27
27
28
28
``` py
@@ -32,9 +32,9 @@ class PriorityQueue(object):
32
32
self ._maxheap = MaxHeap(maxsize)
33
33
34
34
def push (self , priority , value ):
35
- # 注意这里把这个 tuple push进去 ,python 比较 tuple 从第一个开始比较
35
+ # 注意这里把这个 tuple push 进去 ,python 比较 tuple 从第一个开始比较
36
36
# 这样就很巧妙地实现了按照优先级排序
37
- entry = (priority, value)
37
+ entry = (priority, value) # 入队的时候会根据 priority 维持堆的特性
38
38
self ._maxheap.add(entry)
39
39
40
40
def pop (self , with_priority = False ):
You can’t perform that action at this time.
0 commit comments