Last active
December 20, 2015 11:19
-
-
Save tomachalek/6122926 to your computer and use it in GitHub Desktop.
URL shortener (based on md5 alg.)
This file contains 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
# an URL shortener | |
from hashlib import md5 | |
chars = ( | |
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', | |
'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', | |
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', | |
'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' | |
) | |
def id_exists(id): | |
""" | |
This is just a dummy implementation. | |
In practice, some database is queried here | |
""" | |
return False | |
def short(s, min_length=5): | |
x = long('0x' + md5(s).hexdigest(), 16) | |
ans = [] | |
while x > 0: | |
p = x % len(chars) | |
ans.append(chars[p]) | |
x /= len(chars) | |
ans = ''.join([str(x) for x in ans]) | |
max_length = len(ans) | |
i = min_length | |
while id_exists(ans[:i]) and i < max_length: | |
i += 1 | |
return ans[:i] | |
if __name__ == '__main__': | |
import sys | |
print(short(sys.argv[1])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment