API Rate Limiter
Hard · 90 XPImplement allow(timestamps, window, limit): given sorted request timestamps (seconds), return how many requests would be rejected if only limit requests are allowed per rolling window seconds. Process requests in order; a request is rejected if the number of accepted requests in the last window seconds (inclusive) has reached limit. Print the result for the starter data.
Target output
4
Blank · autosaved
PYapi-rate-limiter.py
Keep a list of accepted timestamps; for each request count accepted ones with t > current - window; reject if count >= limit.
def allow(timestamps, window, limit):
accepted = []
rejected = 0
for t in timestamps:
recent = [a for a in accepted if a > t - window]
if len(recent) >= limit:
rejected += 1
else:
accepted.append(t)
return rejected
requests = [1, 2, 2, 3, 4, 10, 10, 11, 12, 12]
print(allow(requests, window=5, limit=3))
Run your code to check it…