-
-
Save DaveIW2034/fa315db74ac1743e3c347b7c029abc7a to your computer and use it in GitHub Desktop.
convert10to35.py
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
# encoding: utf-8 | |
# 用于生成user_id对应的邀请码, user_id唯一 | |
# user_id 在35进制中的表示唯一, 则对应在35位的邀请码唯一 | |
# 将整数转换成35进制字符串所使用的默认密码本 | |
# 密码本字符串(x)长度35, 且须满足密码本字符唯一 | |
# 密码本不能包括 ``0``, (``0`` 用于补足) | |
INT_2_BASE35_CODEBOOK = '此处时26个字符+1-9个数字的混用长度为35的密码本' | |
def int2base35(num, min_len=5, codebook=None): | |
"""把整数转换为35进制的字符串 | |
.. note:: | |
参考文章 https://www.jianshu.com/p/9739ca68b913 | |
>>> int2base35(1) | |
'0000R' | |
>>> int2base35(1, min_len=1) | |
'R' | |
>>> int2base35(100) | |
'000IP' | |
>>> int2base35(10000) | |
'003EF' | |
>>> int2base35(1000000) | |
'0GHH2' | |
>>> int2base35(100000000) | |
'RD6Y6P' | |
>>> int2base35(10000000000) | |
'E2WDEBF' | |
:param int num: 正整数 | |
:param int min_len: 正整数, 转换后长度不足时, 用 `'0'` 补足 | |
:param str codebook: 密码本, 长度35, 不能包含 `'0'`, | |
须满足 `len(codebook) == len(set(codebook))` | |
:return: 转换后的字符串 | |
""" | |
if codebook is None: | |
codebook = INT_2_BASE35_CODEBOOK | |
code, num = '', int(num) | |
while num > 0: | |
mod = num % 35 | |
num = (num - mod) / 35 | |
code = codebook[mod] + code | |
if len(code) < min_len: | |
# 不足位, 左面用 '0' 补全 | |
code = code.rjust(min_len, '0') | |
return code | |
def base35_to_int(code, codebook=None): | |
"""将35进制的字符串转换为正整数 | |
>>> base35_to_int('0000R') | |
1 | |
>>> base35_to_int('R') | |
1 | |
>>> base35_to_int('000IP') | |
100 | |
>>> base35_to_int('003EF') | |
10000 | |
>>> base35_to_int('0GHH2') | |
1000000 | |
>>> base35_to_int('RD6Y6P') | |
100000000 | |
>>> base35_to_int('E2WDEBF') | |
10000000000 | |
:param str code: 由 :func: `int2base35` 生成的字符串 | |
:param str codebook: 密码本, 长度35, 不能包含 `'0'`, | |
须满足 `len(codebook) == len(set(codebook))` | |
:return: 转换后的正整数 | |
:raise ValueError 如果 `code` 中有不在密码本中的字符 | |
""" | |
if codebook is None: | |
codebook = INT_2_BASE35_CODEBOOK | |
code, num = str(code).lstrip('0'), 0 | |
for idx, char in enumerate(reversed(code)): | |
num += codebook.index(char) * pow(35, idx) | |
return num |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment