- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Program to define data structure that supports rate limiting checking for user in Python
Suppose we want to develop a data structure that can build up with an expire time, and supports a function that takes user id and a timestamp. This will check whether a user with given user_id at time given timestamp the request fails or not. It will fail only when the user had a successful request less than the given expire time ago.
So, if the input is like expire = 6 then construct an object obj, and call functions obj.limit(0,10), obj.limit(0,16), obj.limit(0,17) and obj.limit(1,20), then the output will be False, False, True and False respectively because for user 0, initially no request was there so it is false, then at time 16 it is not greater than expire time 6 than last request 10, but at 17 it is true and for the last request, it is for user 1 so initial request is false.
To solve this, we will follow these steps −
Define the constructor . This will take expire
- lastCall := create a dictionary whose default value is -1
- Define a function limit() . This will take uid, timestamp
- last := lastCall[uid]
- if last is same as -1 or (last + expire) <= timestamp, then
- lastCall[uid] := timestamp
- return False
- return True
Let us see the following implementation to get better understanding −
from collections import defaultdict class RateLimit: def __init__(self, expire): self.expire = expire self.lastCall = defaultdict(lambda: -1) def limit(self, uid, timestamp): last = self.lastCall[uid] if last == -1 or last + self.expire <= timestamp: self.lastCall[uid] = timestamp return False return True expire = 6 obj = RateLimit(expire) print(obj.limit(0,10)) print(obj.limit(0,16)) print(obj.limit(0,17)) print(obj.limit(1,20))
RateLimit(6) obj.limit(0,10) obj.limit(0,16) obj.limit(0,17) obj.limit(1,20)
False False True False
- Program to define data structure that supports range sum in Python
- C++ set for user define data type
- Program to define set data structure without using library set class in Python
- Prevent fork bomb by limiting user process in linux
- Python program to define class for complex number objects
- How to define a structure in C#
- Python Program to Implement Queue Data Structure using Linked List
- Define cut off point cut-off rate in accounting.
- What is EDGE (Enhanced Data Rate for GSM Evolution)?
- C++ set for user defined data type?
- Hash Tables for Integer Keys in Data Structure
- C++ Program to Implement Disjoint Set Data Structure
- Java Program to Implement the graph data structure
- Java Program to Implement the queue data structure
- How Can we permanently define user-defined variable for a client in MySQL?