-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathurl56.py
41 lines (36 loc) · 1.13 KB
/
url56.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# Taken from http://leahculver.com/2008/06/17/tiny-urls-based-on-pk/
url56 = '23456789abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'
def to_url56(num):
return dec_to_anybase(num, url56)
def from_url56(value):
return anybase_to_dec(value, url56)
# base 10 to any base using basestring for digits
def dec_to_anybase(num, basestring):
base = len(basestring)
new = ''
current = num
while current >= base:
remainder = current % base
digit = basestring[remainder]
new = '%s%s' % (digit, new)
current = current / base
if basestring[current]: # non-zero indexing
new = '%s%s' % (basestring[current], new)
return new
# any base defined by basestring to base 10
def anybase_to_dec(value, basestring):
base = len(basestring)
n = 0
count = 0
while value:
last = len(value) - 1
digit = value[last]
digit_index = basestring.find(digit)
if digit_index == -1:
raise InvalidURLError
n += digit_index * base**count
value = value[:last]
count += 1
return n
class InvalidURLError(Exception):
pass