Question: URL Shortener Implementation in Python ans # from flask import jsonify,Flask import string id_counter = 1 url_store = {} BASE62 = string.ascii_letters + string.digits def encode_base62(id): if id == 0: return BASE62[0] result = "" while id>0: result = BASE62[id%62] +result id //=62 return result def shorten_url(url): global id_counter code = encode_base62(id_counter) url_store[code] = url id_counter+=1 return f"http://shrtly.in/{code}" actual_url = "https://google.com" short_url = shorten_url(actual_url) print(short_url)
Anoniem
API Rate Limiter (Python) You are tasked with building a rate limiter for an API gateway. Implement a function that ensures no more than 1000 requests per second are processed. If the limit is exceeded, the function should return False; otherwise, return True. ans import time from collections import deque class RateLimiter: def __init__(self, max_requests=1000, window=1.0): self.max_requests = max_requests self.window = window # in seconds self.request_times = deque() def allow_request(self): current_time = time.time() # Remove timestamps outside the current window while self.request_times and self.request_times[0] <= current_time - self.window: self.request_times.popleft() if len(self.request_times) < self.max_requests: self.request_times.append(current_time) return True else: return False # Example usage: limiter = RateLimiter() # Simulate 1005 requests allowed = 0 for _ in range(1005): if limiter.allow_request(): allowed += 1 print("Allowed requests:", allowed) # Output: 1000