Skip to content

Commit 38546f0

Browse files
committed
python builtin PriorityQueue Item
1 parent feb6183 commit 38546f0

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

docs/16_优先级队列/priority_queue.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -154,3 +154,28 @@ def test_buildin_heapq_as_PriorityQueue():
154154
while s_roll:
155155
deque_r = heapq.heappop(s_roll)
156156
print(deque_r)
157+
158+
159+
# python3 没有了 __cmp__ 魔法函数 https://stackoverflow.com/questions/8276983/why-cant-i-use-the-method-cmp-in-python-3-as-for-python-2
160+
class Item:
161+
def __init__(self, key, weight):
162+
self.key, self.weight = key, weight
163+
164+
def __lt__(self, other): # 看其来 heapq 实现只用了 小于 比较,这里定义了就可以 push 一个 item 类
165+
return self.weight < other.weight
166+
167+
def __eq__(self, other):
168+
return self.weight == other.weight
169+
170+
def __str__(self):
171+
return '{}:{}'.format(self.key,self.weight)
172+
173+
174+
def test_heap_item():
175+
import heapq
176+
pq = []
177+
heapq.heappush(pq, Item('c', 3))
178+
heapq.heappush(pq, Item('a', 1))
179+
heapq.heappush(pq, Item('b', 2))
180+
while pq:
181+
print(heapq.heappop(pq))

0 commit comments

Comments
 (0)