File tree Expand file tree Collapse file tree 1 file changed +25
-0
lines changed Expand file tree Collapse file tree 1 file changed +25
-0
lines changed Original file line number Diff line number Diff line change @@ -154,3 +154,28 @@ def test_buildin_heapq_as_PriorityQueue():
154
154
while s_roll :
155
155
deque_r = heapq .heappop (s_roll )
156
156
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 ))
You can’t perform that action at this time.
0 commit comments