File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ from collections import deque
2+
3+
4+ class HitCounter :
5+ """
6+ A counter that records hits (events) and can return
7+ the number of hits in the past 5 minutes (300 seconds).
8+
9+ >>> hc = HitCounter()
10+ >>> hc.hit(1)
11+ >>> hc.hit(2)
12+ >>> hc.hit(300)
13+ >>> hc.get_hits(300)
14+ 3
15+ >>> hc.get_hits(301)
16+ 2
17+ """
18+
19+ def __init__ (self ) -> None :
20+ self .hits : deque [int ] = deque ()
21+
22+ def hit (self , timestamp : int ) -> None :
23+ """Record a hit at the given timestamp (in seconds)."""
24+ self .hits .append (timestamp )
25+
26+ def get_hits (self , timestamp : int ) -> int :
27+ """
28+ Return the number of hits in the past 5 minutes
29+ from the given timestamp.
30+ """
31+ while self .hits and self .hits [0 ] <= timestamp - 300 :
32+ self .hits .popleft ()
33+ return len (self .hits )
34+
35+
36+ if __name__ == "__main__" :
37+ import doctest
38+
39+ doctest .testmod ()
You can’t perform that action at this time.
0 commit comments