Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- BASE62 = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
- def encode(num, alphabet=BASE62):
- """Encode a positive number in Base X
- Arguments:
- - `num`: The number to encode
- - `alphabet`: The alphabet to use for encoding
- """
- if num == 0:
- return alphabet[0]
- arr = []
- base = len(alphabet)
- while num:
- num, rem = divmod(num, base)
- arr.append(alphabet[rem])
- arr.reverse()
- return ''.join(arr)
- def decode(string, alphabet=BASE62):
- """Decode a Base X encoded string into the number
- Arguments:
- - `string`: The encoded string
- - `alphabet`: The alphabet to use for encoding
- """
- base = len(alphabet)
- strlen = len(string)
- num = 0
- idx = 0
- for char in string:
- power = (strlen - (idx + 1))
- num += alphabet.index(char) * (base ** power)
- idx += 1
- return num
- """
- For URL shorteners, I have found that it's better to leave out a few confusing characters like 0Ol1oI etc. Thus I use this alphabet for my URL shortening needs - "23456789abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"
- """
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement