Complete the code to define the main component responsible for limiting requests.
class [1]Limiter: def __init__(self, max_requests, window_seconds): self.max_requests = max_requests self.window_seconds = window_seconds self.requests = {} # user_id -> list of timestamps
The main class is commonly called RateLimiter as it controls the rate of requests.
Complete the code to check if a user can make a request within the rate limit window.
def is_allowed(self, user_id, current_time): if user_id not in self.requests: self.requests[user_id] = [] self.requests[user_id] = [t for t in self.requests[user_id] if t > current_time - [1]] return len(self.requests[user_id]) < self.max_requests
The window to keep requests is defined by self.window_seconds, which is the time frame for rate limiting.
Fix the error in the code that adds a new request timestamp after checking allowance.
def add_request(self, user_id, current_time): if self.is_allowed(user_id, current_time): self.requests[user_id].[1](current_time) return True return False
To add a single timestamp to the list, use append. Other methods are incorrect for this purpose.
Fill both blanks to implement a sliding window rate limiter that removes old requests and checks the count.
def is_allowed(self, user_id, current_time): self.requests[user_id] = [t for t in self.requests.get(user_id, []) if t [1] current_time - self.window_seconds] return len(self.requests[user_id]) [2] self.max_requests
We keep timestamps greater than the window start (t > current_time - window) and allow if count is less than max_requests.
Fill all three blanks to implement a dictionary comprehension that tracks request counts per user within the window.
request_counts = {user: len([t for t in times if t [1] current_time - window]) for user, times in [2].items() if len(times) [3] 0}We filter timestamps greater than the window start, iterate over self.requests, and only include users with more than zero requests.
