python - 将整数转换为具有尽可能少字符的字母数字字符串
问题描述
我正在寻找一种将十进制整数表示形式减少为字符数最少的字符串的方法。
例如,十六进制在十进制数字的顶部使用字母 AF。
hex(123)
有没有一种平滑的方法可以利用所有字母来进一步减少字符串长度?
解决方案
这样您就可以使用自己的字母表,甚至可以将其扩展为 0-9、AZ、az:
递归:
BS="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
def to_base(n, b):
if not n: return "0"
return to_base(n//b, b).lstrip("0") + BS[n%b]
迭代:
BS="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
def to_base(n, b):
res = ""
while n:
res+=BS[n%b]
n//= b
return res[::-1] or "0"
注意:递归版本可以提高RuntimeError: maximum recursion depth exceeded in cmp
非常大的整数和负数。
编码器用法: 参数(n,b)均值(要转换的数字,要使用的基数),例如:
>>> to_base(123,2)
'1111011'
>>> to_base(123,16)
'7B'
>>> to_base(123,len(BS))
'3F'
>>> to_base(1234567890000,16)
'11F71FB0450'
>>> to_base(1234567890000,len(BS))
'FR5HUGK0'
使用 len(BS) 意味着您将使用 BS 变量中的所有字符作为转换的基础。
迭代解码器:
def to_dec(n, b):
res = 0
power = 1
for letter in enumerate(n[::-1]):
i = BS.find(letter)
res += i*power
power *= b
return res
解码器用法: 参数 (n, b) 均值(要转换的数,要使用的基数),例如:
>>> to_dec('1111011',2)
123
>>> to_dec('7B',16)
123
>>> to_dec('3F',len(BS))
123
>>> to_dec('11F71FB0450',16)
1234567890000
>>> to_dec('FR5HUGK0',len(BS))
1234567890000
希望这很有用;)
编辑:添加编码器使用
编辑:添加解码器
编辑:添加解码器使用
推荐阅读
- android - React-Native 中带有实心阴影的文本
- rest - MSGraph API 的代理
- c++ - Arm g++ 交叉编译器错误
- r - 按列填充 R 中的空 data.table
- angular - Angular 5:如何解决 Internet Explorer 11 上的“未定义标题”错误?
- android - 保存 Firestore 对象会引发 InvocationTargetException 错误
- android - 中心底部导航栏图标
- java - OpenJDK 1.8 是否支持椭圆曲线加密?
- c++ - 使用 libpam0g-dev 和 cmake 构建应用程序
- javascript - 使用 findIndex,但从特定位置开始查找