14
14
15
15
| 数据结构/算法 | 语言内置 | 内置库 |
16
16
| ---------------| ---------------------------------| -------------------------------------------------------------------------|
17
- | 线性结构 | list(列表)/tuple(元祖 ) | array(数组,不常用)/collections.namedtuple |
17
+ | 线性结构 | list(列表)/tuple(元组 ) | array(数组,不常用)/collections.namedtuple |
18
18
| 链式结构 | | collections.deque(双端队列) |
19
19
| 字典结构 | dict(字典) | collections.Counter(计数器)/OrderedDict(有序字典)/defaultdict(默认字典) |
20
20
| 集合结构 | set(集合)/frozenset(不可变集合) | |
@@ -152,6 +152,7 @@ def test_buildin_PriorityQueue(): # python3
152
152
def test_buildin_heapq_as_PriorityQueue ():
153
153
"""
154
154
测试使用 heapq 实现优先级队列,保存一个 tuple 比较元素(tuple第一个元素是优先级)
155
+ 实际上是利用了元组tuple比较从第一个开始比较的性质
155
156
"""
156
157
import heapq
157
158
s_roll = []
@@ -169,15 +170,16 @@ class Item:
169
170
def __init__ (self , key , weight ):
170
171
self .key, self .weight = key, weight
171
172
172
- def __lt__ (self , other ): # 看其来 heapq 实现只用了 小于 比较,这里定义了就可以 push 一个 item 类
173
+ def __lt__ (self , other ): # heapq 源码实现只用了 小于 比较,这里定义了就可以 push 一个 item 类
173
174
return self .weight < other.weight
174
175
175
- def __eq__ (self , other ):
176
+ def __eq__ (self , other ): # 这个可以省略,只要定义了 __lt__ 魔法函数就可以了
176
177
return self .weight == other.weight
177
178
178
179
def __str__ (self ):
179
180
return ' {} :{} ' .format(self .key,self .weight)
180
181
182
+ # Item.__lt__ = lambda self, other: self.weight < other.weight # 对于已有的类,直接加一句就可以实现作为 heap item 了
181
183
182
184
def test_heap_item ():
183
185
"""
0 commit comments