encode-and-decode-tinyurl py3

This commit is contained in:
2022-04-24 02:10:44 +05:30
parent 731af263a4
commit 60066617e3
3 changed files with 67 additions and 1 deletions

View 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))