-
Notifications
You must be signed in to change notification settings - Fork 17
/
encode-and-decode-tinyurl.py
43 lines (31 loc) · 1.16 KB
/
encode-and-decode-tinyurl.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import random
import string
from typing import List, Dict
from functools import lru_cache
class Codec:
url_length = 8
url_symbols = string.ascii_lowercase + string.ascii_uppercase + string.digits
url_max_value = len(url_symbols) ** 8
@lru_cache(None)
def map(self) -> Dict[str, str]:
return {}
def encode(self, longUrl: str) -> str:
"""Encodes a URL to a shortened URL.
"""
while True: # This potentially give infinite complexity
number = random.randint(0, self.url_max_value)
url_letters: List[str] = []
for _ in range(self.url_length):
url_letters.append(self.url_symbols[number % len(self.url_symbols)])
number //= len(self.url_symbols)
url = "".join(url_letters)
if url not in self.map():
self.map()[url] = longUrl
return url
def decode(self, shortUrl: str) -> str:
"""Decodes a shortened URL to its original URL.
"""
return self.map()[shortUrl]
# Your Codec object will be instantiated and called as such:
# codec = Codec()
# codec.decode(codec.encode(url))