实现说明
逻辑集中在函数 track_top3里。
这个文件只在 for value in samples 里循环。
使用要点
- 全程不引用第三方外部库,所有调用均来自内置 API。
- 演示输出是带标签的(
top-3 latencies:、heappushpop(5): popped=、heapreplace(5): popped=),每个操作都会留下自己的一行标注。 - 调用方只需要
track_top3——其余都是内部实现。
常见问题
这个示例需要哪些包?
一个都不用。代码用到的符号都在标准库里解析。 文件在加载时定义 track_top3。
主签名形如 def track_top3(samples: list[int]) -> list[int]
代码示例
import heapq
# Keep the top-3 highest latencies without sorting the full stream
def track_top3(samples: list[int]) -> list[int]:
top = []
for value in samples:
if len(top) < 3:
heapq.heappush(top, value)
else:
# heappushpop checks the incoming item before discarding the smallest
heapq.heappushpop(top, value)
return sorted(top, reverse=True)
stream = [18, 92, 41, 7, 130, 64, 15, 110]
print("top-3 latencies:", track_top3(stream))
# Contrast: heapreplace pops the root BEFORE pushing the new element
h_pushpop = [10, 30, 50]
h_replace = [10, 30, 50]
out_a = heapq.heappushpop(h_pushpop, 5)
out_b = heapq.heapreplace(h_replace, 5)
print("heappushpop(5): popped=", out_a, "heap=", sorted(h_pushpop))
print("heapreplace(5): popped=", out_b, "heap=", sorted(h_replace))