Skip to content

Instantly share code, notes, and snippets.

@phil-r
Created September 11, 2014 14:48
Show Gist options
  • Save phil-r/b0d44875a36232f9f556 to your computer and use it in GitHub Desktop.
Save phil-r/b0d44875a36232f9f556 to your computer and use it in GitHub Desktop.
from string import ascii_letters, digits
ALPHABET = digits + ascii_letters
__author__ = 'phil'
def convert_to_code(number, minimal_length=1, alphabet=ALPHABET):
"""Converts a decimal id number into a shortened code."""
base = len(alphabet) # base to convert to
chars = []
while number:
chars.append(alphabet[number % base])
number //= base
chars.reverse() # moved right to left, so reverse order
res = ''.join(chars) # convert stored characters to single string
return ''.join(('0' * (minimal_length - len(res)), res))
def resolve_to_id(code, alphabet=ALPHABET):
"""Converts the shortened code back to an id number in decimal form."""
base = len(alphabet)
size = len(code)
number = 0
for i in range(0, size): # convert from higher base back to decimal
number += alphabet.index(code[i]) * (base ** (size - i - 1))
return number
print convert_to_code(140906) # AEG
print resolve_to_id('AEG') # 140906
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment