2025-09-10:仓库迁移

This commit is contained in:
2025-09-10 16:12:45 +08:00
parent e0e49b0ac9
commit 3130e336a1
146 changed files with 4066 additions and 0 deletions

View File

@@ -0,0 +1,43 @@
import heapq
# 优先级队列(使用小根堆实现)
class PriorityQueue:
def __init__(self):
self._queue = []
# 由于优先级在比较大小时可能相同造成比较失败维护一个下标index来进行二级辨识
self._index = 0
# 由于heapq的原理是生成一个小根堆所以优先级取负这样优先级越大堆识别到的优先级越小引入index在优先级相同时比较入栈先后顺序
def push(self, item, priority):
heapq.heappush(self._queue, (-priority, self._index, item))
self._index += 1
# 弹出堆顶值
def pop(self):
return heapq.heappop(self._queue)[-1]
# 在Python中实例化对象是不可以直接进行比较的例如
class Item:
def __init__(self, name):
self.name = name
def __repr__(self):
return 'Item {!r}'.format(self.name)
# a = Iter('foo') b = Iter('bar'), 进行a<b比较会输出报错
# 一个优先级队列的简单调用示例
if __name__ == "__main__":
q = PriorityQueue()
q.push(Item("foo"), 1)
q.push(Item("bar"), 5)
q.push(Item("spam"), 4)
q.push(Item("grok"), 1)
a = q.pop()
b = q.pop()
c = q.pop()
d = q.pop()
print(a)