Last active
July 17, 2019 05:41
-
-
Save lokesh1729/d96653ea1358a8dc6360c155cc15e7d7 to your computer and use it in GitHub Desktop.
#python #url #shortid #short #base62 #base64
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
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" | |
""" |
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
""" | |
This module contains functions to transform a number to string and vice-versa | |
""" | |
BASE = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" | |
LEN_BASE = len(BASE) | |
def encode(num): | |
""" | |
This function encodes the given number into alpha numeric string | |
""" | |
if num < LEN_BASE: | |
return BASE[num] | |
return BASE[num % LEN_BASE] + encode(num//LEN_BASE) | |
def decode_recursive(string, index): | |
""" | |
recursive util function for decode | |
""" | |
if not string or index >= len(string): | |
return 0 | |
return (BASE.index(string[index]) * LEN_BASE ** index) + decode_recursive(string, index + 1) | |
def decode(string): | |
""" | |
This function decodes given string to number | |
""" | |
return decode_recursive(string, 0) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment