Skip to content

Instantly share code, notes, and snippets.

@mylons
Created November 20, 2018 06:44
Show Gist options
  • Select an option

  • Save mylons/5b5a159d15ca64eb5722674028367894 to your computer and use it in GitHub Desktop.

Select an option

Save mylons/5b5a159d15ca64eb5722674028367894 to your computer and use it in GitHub Desktop.
from collections import defaultdict
import random
import string
alphabet = string.ascii_letters + '0123456789'
class Codec:
def __init__(self):
self.urls = defaultdict(str)
def encode(self, longUrl):
"""Encodes a URL to a shortened URL.
:type longUrl: str
:rtype: str
"""
hash = ''.join(random.choices(alphabet, k=6))
if hash in self.urls:
return self.urls[hash]
else:
self.urls[hash] = longUrl
return f"http://tinyurl.com/{hash}"
def decode(self, shortUrl):
"""Decodes a shortened URL to its original URL.
:type shortUrl: str
:rtype: str
"""
hash = shortUrl.split('/')[-1]
return self.urls[hash]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment