encode-and-decode-tinyurl py3
This commit is contained in:
37
0535_encode-and-decode-tinyurl/python3/solution.py
Normal file
37
0535_encode-and-decode-tinyurl/python3/solution.py
Normal file
@@ -0,0 +1,37 @@
|
||||
# NOTE: This one is an open-ended question, and relevant to system design. Refer
|
||||
# the notes.
|
||||
|
||||
import string
|
||||
import random
|
||||
|
||||
class Codec:
|
||||
store = {}
|
||||
base = 'https://tiny.url/'
|
||||
|
||||
def encode(self, longUrl: str) -> str:
|
||||
"""Encodes a URL to a shortened URL.
|
||||
"""
|
||||
tiny = None
|
||||
|
||||
while True:
|
||||
tiny = ''.join(random.choices(string.ascii_letters + string.digits, k = 5))
|
||||
|
||||
if tiny not in self.store:
|
||||
break
|
||||
|
||||
self.store[tiny] = longUrl
|
||||
|
||||
return f'{self.base}{tiny}'
|
||||
|
||||
|
||||
def decode(self, shortUrl: str) -> str:
|
||||
"""Decodes a shortened URL to its original URL.
|
||||
"""
|
||||
_, tiny = shortUrl.split(self.base)
|
||||
|
||||
return self.store[tiny]
|
||||
|
||||
|
||||
# Your Codec object will be instantiated and called as such:
|
||||
# codec = Codec()
|
||||
# codec.decode(codec.encode(url))
|
||||
Reference in New Issue
Block a user