Created
November 20, 2018 06:44
-
-
Save mylons/5b5a159d15ca64eb5722674028367894 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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