Created
April 5, 2019 15:38
-
-
Save theeluwin/f6d92d4820ab9847e7d0266332c57e97 to your computer and use it in GitHub Desktop.
Convert Instagram long id into shortcode and vice versa.
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
| # -*- coding: utf-8 -*- | |
| # ported from: https://gist.github.com/sclark39/9daf13eea9c0b381667b61e3d2e7bc11 | |
| class Shortcoder(object): | |
| LOWER = 'abcdefghijklmnopqrstuvwxyz' | |
| UPPER = LOWER.upper() | |
| NUMBERS = '0123456789' | |
| def __init__(self): | |
| self.ALPHABET = self.UPPER + self.LOWER + self.NUMBERS + '-_' | |
| self.reverse = {self.ALPHABET[i]: i for i in range(len(self.ALPHABET))} | |
| self.radix = len(self.ALPHABET) | |
| def lid2code(self, lid): | |
| lid = int(lid) | |
| code = [] | |
| while True: | |
| remainder = lid % self.radix | |
| lid = lid // self.radix | |
| code.append(self.ALPHABET[remainder]) | |
| if not lid: | |
| break | |
| return ''.join(code[::-1]) | |
| def code2lid(self, code): | |
| code = str(code) | |
| lid = 0 | |
| exponent = 1 | |
| code = code[::-1] | |
| for c in code: | |
| lid = lid + exponent * self.reverse[c] | |
| exponent = exponent * self.radix | |
| return lid | |
| if __name__ == '__main__': | |
| shortcoder = Shortcoder() | |
| lid = 908540701891980503 | |
| code = 'ybyPRoQWzX' | |
| assert lid == shortcoder.code2lid(code) | |
| assert code == shortcoder.lid2code(lid) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment