Created
April 28, 2020 11:59
-
-
Save adw0rd/8294a5e0eb406f6c40d23e440ae2f501 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
class InstagramIdCodec: | |
ENCODING_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_" | |
@staticmethod | |
def encode(num, alphabet=ENCODING_CHARS): | |
"""Covert a numeric value to a shortcode.""" | |
num = int(num) | |
if num == 0: | |
return alphabet[0] | |
arr = [] | |
base = len(alphabet) | |
while num: | |
rem = num % base | |
num //= base | |
arr.append(alphabet[rem]) | |
arr.reverse() | |
return "".join(arr) | |
@staticmethod | |
def decode(shortcode, alphabet=ENCODING_CHARS): | |
"""Covert a shortcode to a numeric value.""" | |
base = len(alphabet) | |
strlen = len(shortcode) | |
num = 0 | |
idx = 0 | |
for char in shortcode: | |
power = strlen - (idx + 1) | |
num += alphabet.index(char) * (base ** power) | |
idx += 1 | |
return num |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment