Created
November 8, 2013 03:26
-
-
Save chunyan/7365854 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
import math | |
import sys | |
import uuid | |
# this is taken from: https://gist.github.com/bhelx/778542 | |
# modified to support long | |
class UrlShortener: | |
BASE = 62 | |
UPPERCASE_OFFSET = 55 | |
LOWERCASE_OFFSET = 61 | |
DIGIT_OFFSET = 48 | |
@staticmethod | |
def true_ord(char): | |
""" | |
Turns a digit [char] in character representation | |
from the number system with base [BASE] into an integer. | |
""" | |
if char.isdigit(): | |
return ord(char) - UrlShortener.DIGIT_OFFSET | |
elif 'A' <= char <= 'Z': | |
return ord(char) - UrlShortener.UPPERCASE_OFFSET | |
elif 'a' <= char <= 'z': | |
return ord(char) - UrlShortener.LOWERCASE_OFFSET | |
else: | |
raise ValueError("%s is not a valid character" % char) | |
@staticmethod | |
def true_chr(integer): | |
""" | |
Turns an integer [integer] into digit in base [BASE] | |
as a character representation. | |
""" | |
if integer < 10: | |
return chr(integer + UrlShortener.DIGIT_OFFSET) | |
elif 10 <= integer <= 35: | |
return chr(integer + UrlShortener.UPPERCASE_OFFSET) | |
elif 36 <= integer < 62: | |
return chr(integer + UrlShortener.LOWERCASE_OFFSET) | |
else: | |
raise ValueError("%d is not a valid integer in the range of base %d" % (integer, UrlShortener.BASE)) | |
@staticmethod | |
def saturate(key): | |
""" | |
Turn the base [BASE] number [key] into an integer | |
""" | |
int_sum = 0 | |
reversed_key = key[::-1] | |
for idx, char in enumerate(reversed_key): | |
int_sum += UrlShortener.true_ord(char) * (UrlShortener.BASE ** idx) # don't use math.pow, use python built-in pow to handle large int | |
return int_sum | |
@staticmethod | |
def dehydrate(integer): | |
""" | |
Turn an integer [integer] into a base [BASE] number | |
in string representation | |
""" | |
# we won't step into the while if integer is 0 | |
# so we just solve for that case here | |
if integer == 0: | |
return '0' | |
string = "" | |
while integer > 0: | |
remainder = integer % UrlShortener.BASE | |
string = UrlShortener.true_chr(remainder) + string | |
integer /= UrlShortener.BASE | |
return string | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment