-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdesign-hit-counter.py
More file actions
63 lines (53 loc) · 1.64 KB
/
design-hit-counter.py
File metadata and controls
63 lines (53 loc) · 1.64 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
from collections import OrderedDict
class HitCounter(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.od = OrderedDict()
self.total = 0
self.last = 300
def hit(self, timestamp):
"""
Record a hit.
@param timestamp - The current timestamp (in seconds granularity).
:type timestamp: int
:rtype: void
"""
if timestamp < self.last - 299:
return
if timestamp > self.last:
self.last = timestamp
for t in self.od:
if t < self.last - 299:
self.total -= self.od[t]
del(self.od[t])
else:
break
if timestamp in self.od:
self.od[timestamp] += 1
else:
self.od[timestamp] = 1
self.total += 1
def getHits(self, timestamp):
"""
Return the number of hits in the past 5 minutes.
@param timestamp - The current timestamp (in seconds granularity).
:type timestamp: int
:rtype: int
"""
if timestamp < self.last - 299:
return 0
if timestamp > self.last:
self.last = timestamp
for t in self.od:
if t < self.last - 299:
self.total -= self.od[t]
del(self.od[t])
else:
break
return self.total
# Your HitCounter object will be instantiated and called as such:
# obj = HitCounter()
# obj.hit(timestamp)
# param_2 = obj.getHits(timestamp)