-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathlogger-rate-limiter.py
84 lines (66 loc) · 2.72 KB
/
logger-rate-limiter.py
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
from collections import Counter, deque, defaultdict
class Logger:
def __init__(self):
"""
Initialize your data structure here.
"""
self.hashmap = defaultdict(lambda: -11)
def shouldPrintMessage(self, timestamp: int, message: str) -> bool:
"""
Returns true if the message should be printed in the given timestamp, otherwise returns false.
If this method returns false, the message will not be printed.
The timestamp is in seconds granularity.
"""
if timestamp - self.hashmap[message] >= 10:
self.hashmap[message] = timestamp
return True
else:
return False
class MessageBucket:
def __init__(self, timestamp: int):
self.timestamp = timestamp
self.messages: Counter = Counter()
def __repr__(self) -> str:
return f"MessageBucket({self.timestamp}), messages: {self.messages}"
class Logger2:
def __init__(self):
"""
Initialize your data structure here.
"""
self._message_counter: Counter = Counter()
self._message_bucket_queue: deque = deque()
self._keep_timestamps = 10
def _drop_old_timestamps(self, timestamp: int) -> None:
while (
self._message_bucket_queue
and self._message_bucket_queue[0].timestamp <= timestamp - 10
):
message_bucket = self._message_bucket_queue.popleft()
for message, count in message_bucket.messages.items():
self._message_counter[message] -= count
def _add_new_message_bucket(self, timestamp: int) -> None:
if (
not self._message_bucket_queue
or self._message_bucket_queue[-1].timestamp != timestamp
):
message_bucket = MessageBucket(timestamp)
self._message_bucket_queue.append(message_bucket)
def _add_new_message(self, message: str) -> None:
message_bucket = self._message_bucket_queue[-1]
message_bucket.messages[message] += 1
self._message_counter[message] += 1
def shouldPrintMessage(self, timestamp: int, message: str) -> bool:
"""
Returns true if the message should be printed in the given timestamp, otherwise returns false.
If this method returns false, the message will not be printed.
The timestamp is in seconds granularity.
"""
self._drop_old_timestamps(timestamp)
if self._message_counter[message] == 0:
self._add_new_message_bucket(timestamp)
self._add_new_message(message)
return True
return False
# Your Logger object will be instantiated and called as such:
# obj = Logger()
# param_1 = obj.shouldPrintMessage(timestamp,message)