Created
September 11, 2014 14:48
-
-
Save phil-r/b0d44875a36232f9f556 to your computer and use it in GitHub Desktop.
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
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