|
32 | 32 | - 正确初始化一个二维数组:`dp = [[0 for _ in range(col)] for _ in range(row)]`,不要用 `dp = [[0] * n] * m`, 否则里边都
|
33 | 33 | 引用的同一个 list,修改一个都会变
|
34 | 34 | - python在数值范围建议用:`MAXINT = 2**63-1; MININT = -2**63` 。因为 python2 sys.maxint 和 python3 sys.maxsize 不统一
|
| 35 | +- 优先级队列:使用内置的 heapq ,定义一个 Item 类实现"小于" 魔术方法就可以实现 |
35 | 36 |
|
36 | 37 |
|
37 | 38 | # 链表题目调试函数
|
@@ -89,3 +90,67 @@ def print_list(head):
|
89 | 90 | res += "nil"
|
90 | 91 | print(res)
|
91 | 92 | ```
|
| 93 | + |
| 94 | + |
| 95 | +# 内置库实现优先级队列的三种方式 |
| 96 | + |
| 97 | +```py |
| 98 | +def test_buildin_PriorityQueue(): # python3 |
| 99 | + """ |
| 100 | + 测试内置的 PriorityQueue |
| 101 | + https://pythonguides.com/priority-queue-in-python/ |
| 102 | + """ |
| 103 | + from queue import PriorityQueue |
| 104 | + q = PriorityQueue() |
| 105 | + q.put((10, 'Red balls')) |
| 106 | + q.put((8, 'Pink balls')) |
| 107 | + q.put((5, 'White balls')) |
| 108 | + q.put((4, 'Green balls')) |
| 109 | + while not q.empty(): |
| 110 | + item = q.get() |
| 111 | + print(item) |
| 112 | + |
| 113 | + |
| 114 | +def test_buildin_heapq_as_PriorityQueue(): |
| 115 | + """ |
| 116 | + 测试使用 heapq 实现优先级队列,保存一个 tuple 比较元素(tuple第一个元素是优先级) |
| 117 | + """ |
| 118 | + import heapq |
| 119 | + s_roll = [] |
| 120 | + heapq.heappush(s_roll, (4, "Tom")) |
| 121 | + heapq.heappush(s_roll, (1, "Aruhi")) |
| 122 | + heapq.heappush(s_roll, (3, "Dyson")) |
| 123 | + heapq.heappush(s_roll, (2, "Bob")) |
| 124 | + while s_roll: |
| 125 | + deque_r = heapq.heappop(s_roll) |
| 126 | + print(deque_r) |
| 127 | + |
| 128 | + |
| 129 | +# python3 没有了 __cmp__ 魔法函数 https://stackoverflow.com/questions/8276983/why-cant-i-use-the-method-cmp-in-python-3-as-for-python-2 |
| 130 | +class Item: |
| 131 | + def __init__(self, key, weight): |
| 132 | + self.key, self.weight = key, weight |
| 133 | + |
| 134 | + def __lt__(self, other): # 看其来 heapq 实现只用了 小于 比较,这里定义了就可以 push 一个 item 类 |
| 135 | + return self.weight < other.weight |
| 136 | + |
| 137 | + def __eq__(self, other): |
| 138 | + return self.weight == other.weight |
| 139 | + |
| 140 | + def __str__(self): |
| 141 | + return '{}:{}'.format(self.key,self.weight) |
| 142 | + |
| 143 | + |
| 144 | +def test_heap_item(): |
| 145 | + """ |
| 146 | + 测试使用 Item 类实现优先级队列,因为 heapq 内置使用的是小于运算法, |
| 147 | + 重写魔术 < 比较方法即可实现 |
| 148 | + """ |
| 149 | + import heapq |
| 150 | + pq = [] |
| 151 | + heapq.heappush(pq, Item('c', 3)) |
| 152 | + heapq.heappush(pq, Item('a', 1)) |
| 153 | + heapq.heappush(pq, Item('b', 2)) |
| 154 | + while pq: |
| 155 | + print(heapq.heappop(pq)) |
| 156 | +``` |
0 commit comments