将整数转换为包含尽可能少字符的字母数字字符串

问题描述

我正在寻找一种方法来将十进制整数表示形式简化为字符最少的字符串。

例如十六进制在十进制数字的顶部使用字母A-F。

hex(123)

有没有一种平滑的方法来利用所有字母来进一步减少字符串长度?

解决方法

这样您就可以使用自己的字母,甚至可以将其扩展为0-9,A-Z和a-z:

递归:

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

希望这很有用;)

编辑:添加了编码器用法
编辑:添加了解码器
编辑:添加了解码器用法