Skip to content

Instantly share code, notes, and snippets.

@thoslin
Created October 30, 2013 06:26
Show Gist options
  • Save thoslin/7227969 to your computer and use it in GitHub Desktop.
Save thoslin/7227969 to your computer and use it in GitHub Desktop.
Python implementation for generating Tiny URL- and bit.ly-like URLs
#!/usr/bin/env python
_alphabet = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM0123456789"
_base = len(_alphabet)
def encode(n):
"""
Encode a number using the alphabet above
>>> encode(0)
'q'
>>> encode(61)
'9'
>>> encode(23423)
'uyB'
"""
r = []
r1 = n / _base
r2 = n % _base
r.insert(0, r2)
while r1 >= _base:
n = r1
r1 = n / _base
r2 = n % _base
r.insert(0, r2)
if r1:
r.insert(0, r1)
return "".join([_alphabet[i] for i in r])
def decode(s):
"""
Decode a string into a base 10 number
>>> decode('q')
0
>>> decode('9')
61
>>> decode('uyB')
23423
"""
s = s[::-1]
return sum([_alphabet.index(i)*_base**s.index(i) for i in s])
if __name__ == "__main__":
import doctest
doctest.testmod()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment