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 11# 优先级队列
22你可能比较奇怪,队列不是早就讲了嘛。这里之所以放到这里讲优先级队列,是因为虽然名字有队列,
3- 其实使用的是堆来实现的 。上一章讲完了堆,这一章我们就来实现一个优先级队列 。
3+ 但其实是使用堆来实现的 。上一章讲完了堆,这一章我们就趁热打铁来实现一个优先级队列 。
44
55
66# 实现优先级队列
1111def test_priority_queue ():
1212 size = 5
1313 pq = PriorityQueue(size)
14- pq.push(5 , ' purple' )
14+ pq.push(5 , ' purple' ) # priority, value
1515 pq.push(0 , ' white' )
1616 pq.push(3 , ' orange' )
1717 pq.push(1 , ' black' )
@@ -22,7 +22,7 @@ def test_priority_queue():
2222 assert res == [' purple' , ' orange' , ' black' , ' white' ]
2323```
2424
25- 上边就是期望的行为,然后编写优先级队列,按照出队的时候最大优先级先出对的顺序 :
25+ 上边就是期望的行为,写完测试代码后我们来编写优先级队列的代码,按照出队的时候最大优先级先出的顺序 :
2626
2727
2828``` py
@@ -32,9 +32,9 @@ class PriorityQueue(object):
3232 self ._maxheap = MaxHeap(maxsize)
3333
3434 def push (self , priority , value ):
35- # 注意这里把这个 tuple push进去 ,python 比较 tuple 从第一个开始比较
35+ # 注意这里把这个 tuple push 进去 ,python 比较 tuple 从第一个开始比较
3636 # 这样就很巧妙地实现了按照优先级排序
37- entry = (priority, value)
37+ entry = (priority, value) # 入队的时候会根据 priority 维持堆的特性
3838 self ._maxheap.add(entry)
3939
4040 def pop (self , with_priority = False ):
You can’t perform that action at this time.
0 commit comments