Skip to content

Instantly share code, notes, and snippets.

@maebert
Created February 20, 2013 20:13
Show Gist options
  • Save maebert/4999112 to your computer and use it in GitHub Desktop.
Save maebert/4999112 to your computer and use it in GitHub Desktop.
Gets the shortest unique code (e.g. for URL shorteners) that avoids confusion between characters (such as I and 1, 0 and O).
def get_code(num, alphabet="23456789ABCDEFGHJKLMNPQRSTUVWXYZ"):
base = len(alphabet)
result = ""
num, rem = divmod(num, base)
while num:
result += alphabet[rem]
num, rem = divmod(num, base)
result += alphabet[rem]
return result[::-1]
rows_in_db = 12345
new_shortcode = get_code(rows_in_db + 1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment