How can a fixed-capacity candidate pool keep its three largest scores?
heappushpop inserts a candidate and returns the smallest element, preserving the min-heap's size.
Python example and interpretation
Starting with 3,5,8, a seven displaces three and a one is discarded. Heap storage is only partially ordered, so sort separately for display.
from heapq import heapify,heappushpop
h=[3,5,8]
heapify(h)
heappushpop(h,7)
heappushpop(h,1)
sorted(h,reverse=True)Result [8, 7, 5]
中文
固定容量的候选池如何只保留最大的三个分数?
heappushpop 在最小堆中加入一项并返回最小项,堆的大小保持不变。
Python 算例与适用条件
初始分数 3、5、8,遇到 7 后淘汰 3,遇到 1 后直接淘汰 1。堆内部只保证堆序,展示前要另行排序。
from heapq import heapify,heappushpop
h=[3,5,8]
heapify(h)
heappushpop(h,7)
heappushpop(h,1)
sorted(h,reverse=True)结果 [8, 7, 5]