实现说明
底层就是类 RecentCalls和函数 __init__、ping。
驱动整个流程的是 while self._times and t - self._times[0] > 3000 这一个循环。
使用要点
- 每一步打印都带着自己的标签:
ping(。 ping是公开入口,文件里其余部分都是为它服务的内部实现。
常见问题
有第三方依赖吗?
没有。依赖清单是空的,代码只用标准库。 文件在加载时定义 __init__、ping。
签名一览:def ping(self, t: int) -> int
核心语句
def ping(self, t: int) -> int:
# evict every timestamp older than the window in one amortized pass
while self._times and t - self._times[0] > 3000:
self._times.popleft()
self._times.append(t)
return len(self._times)
def __init__(self):
self._times = deque()
代码示例
from collections import deque
class RecentCalls:
"""Counts pings within the last 3000 ms using a monotonic queue."""
def __init__(self):
self._times = deque()
def ping(self, t: int) -> int:
# evict every timestamp older than the window in one amortized pass
while self._times and t - self._times[0] > 3000:
self._times.popleft()
self._times.append(t)
return len(self._times)
counter = RecentCalls()
for t in [1, 100, 3001, 3002, 7000]:
print(f"ping({t}) -> {counter.ping(t)}")