Skip to content

Instantly share code, notes, and snippets.

@priyankvex
Created December 14, 2018 15:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save priyankvex/b53321946cc6d7df65af23bafca75d43 to your computer and use it in GitHub Desktop.
Save priyankvex/b53321946cc6d7df65af23bafca75d43 to your computer and use it in GitHub Desktop.
Scamming the coding interview: Problem 003: URL shortner
"""
Scamming the coding interview
"""
chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'
memory_db = {}
def get_shorten_url(long_url, url_id):
"""
Returns a shortened URL for a given original URL
"""
url_key = url_id
shorten_url_code = ""
while url_id > 0:
shorten_url_code = chars[url_id % 62] + shorten_url_code
url_id = int(url_id / 62)
memory_db[url_key] = long_url
return shorten_url_code
def get_original_url(shorten_url_code):
"""
Returns the original URL for a given shortened URL
"""
url_number = 0
shorten_url_code = shorten_url_code[::-1]
for i, character in enumerate(shorten_url_code):
if 'a' <= character <= 'z':
temp = (62 ** i) * (int(ord(character) - ord('a')))
if 'A' <= character <= 'Z':
temp = (62 ** i) * (int(ord(character) - ord('A')) + 26)
if '1' <= character <= '9':
temp = (62 ** i) + (int(ord(character) - ord('1')) + 42)
url_number += temp
url = memory_db.get(url_number)
return url
if __name__ == '__main__':
long_url = "https://priyankvex.com"
url_id = 123456789
shorten_url = get_shorten_url(long_url, url_id)
print(shorten_url)
original_url = get_original_url(shorten_url)
print(original_url)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment