Skip to content

Commit 5363421

Browse files
committed
Create rate_checker.py
1 parent a9c6f79 commit 5363421

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

rate_checker.py

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
""" Create a rate checker which takes actions, for number of occurrences, and seconds, for time in which those actions have occurred. Using a check method return True if it is called at least N times (actions) in up to Q seconds. Otherwise, return False. """
2+
3+
import datetime
4+
from time import sleep
5+
6+
7+
class RateChecker(object):
8+
9+
def __init__(self, actions, seconds):
10+
self.actions = actions
11+
self.seconds = seconds
12+
self.times = [] # Queue needed to keep track of how many times it's being checked
13+
14+
def check(self):
15+
"""
16+
>>> clicks = RateChecker(3, 14)
17+
>>> clicks.check()
18+
>>> clicks.check()
19+
>>> clicks.check()
20+
>>> clicks.check()
21+
False
22+
23+
"""
24+
current_time = datetime.datetime.now().time()
25+
self.times.append(current_time) # Append each check time to the queue
26+
27+
if len(self.times) > self.actions: # First check if the queue is greater than the number of actions
28+
return False # Returning false here gives a quick win
29+
30+
return datetime.datetime.strptime(str(current_time), "%H:%M:%S.%f") - datetime.datetime.strptime(str(self.times.pop()), "%H:%M:%S.%f") <= datetime.timedelta(seconds=self.seconds) # Check times in the queue
31+
# (Slower approach if the queue is really huge, hence why queue length vs. actions should be checked first.)
32+
33+
34+
35+
if __name__ == "__main__":
36+
import doctest
37+
results = doctest.testmod()
38+
39+
if not results.failed:
40+
print "All tests passed!"

0 commit comments

Comments
 (0)