python import random import string class URLShortener: def __init__(self): self.mapping = {} def shorten_url(self, long_url): short_url = self.generate_short_url() self.mapping[short_url] = long_url return short_url def generate_short_url(self): chars = string.ascii_letters + string.digits short_url = ''.join(random.choice(chars) for _ in range(8)) return short_url def redirect_to_long_url(self, short_url): if short_url in self.mapping: long_url = self.mapping[short_url] print("Redirecting to:", long_url) else: print("Short URL not found.") shortener = URLShortener() long_url = "http://example.com/very/long/url/that/we/want/to/shorten" short_url = shortener.shorten_url(long_url) print("Short URL:", short_url) shortener.redirect_to_long_url(short_url)


上一篇:
下一篇:
切换中文