【问题标题】:Convert an integer to an alphanumeric string with as few characters as possible将整数转换为具有尽可能少字符的字母数字字符串
【发布时间】:2021-01-09 09:30:56
【问题描述】:

我正在寻找一种方法来将十进制整数表示形式减少为具有尽可能少的字符的字符串。

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

hex(123)

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

【问题讨论】:

标签: python integer representation


【解决方案1】:

这样您就可以使用自己的字母表,甚至可以将其扩展为 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

希望这是有用的;)

编辑:添加编码器使用
编辑:添加解码器
编辑:添加解码器使用

【讨论】:

  • 谢谢!这有点像我的联盟。我无法理解 (s, b) 参数。你能添加一个例子吗?之后你将如何解码。
猜你喜欢
  • 2022-01-18
  • 2015-01-03
  • 2017-12-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-08
  • 2018-02-01
  • 1970-01-01
相关资源
最近更新 更多