是否有快速 Python 函数可以将数字转换为不同的基数?

Is there a quick Python function for turning numbers into different bases?

我正在编写一个代码来检查一个数字以 2-10 为底的回文数有多少次。是否有 python 将数字转换为不同基数的函数?

我已经尝试过手动创建一个函数,但是太慢了。

baseChars="0123456789"
def toBase(n, b): 
    return "0" if not n else toBase(n//b, b).lstrip("0") + baseChars[n%b]

我希望 toBase 函数 return 以 2-10 的所有基数表示的数字。我想避免使用 NumPy

这在 NumPy 中可用 base_repr():

import numpy as np
[np.base_repr(100, base) for base in range(2,11)]

结果:

['1100100', '10201', '1210', '400', '244', '202', '144', '121', '100']

我不认为标准库中有任何单一函数可以执行此操作。但是在 a different project 为我自己的一个 类 工作时,我不得不解决这类问题,我的解决方案如下所示:

def _base(decimal, base):
    """
    Converts a number to the given base, returning a string.
    Taken from 
    :param decimal: an integer
    :param base: The base to which to convert that integer
    :return: A string containing the base-base representation of the given number
    """
    li = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    other_base = ""
    while decimal != 0:
        other_base = li[decimal % base] + other_base
        decimal = decimal // base
    if other_base == "":
        other_base = "0"
    return other_base

def palindromes(num, bases=range(2, 11)):
    """
    Checks if the given number is a palindrome in every given base, in order. 
    Returns the sublist of bases for which the given number is a palindrome, 
    or an empty list if it is not a palindrome in any base checked.
    :param num: an integer to be converted to various bases
    :param bases: an iterable containing ints representing bases
    """
    return [i for i in bases if _base(num, i) == _base(num, i)[::-1]]

(最后一条语句的不太简洁的版本(扩展 for 循环)如下所示):

r = []
for i in bases:
    b = _base(num, i)
    if b == b[::-1]:
        r.append(i)
return r

在你的例子中,如果你只想要一个以各种基数表示的整数列表,代码会更简单:

reps = {b: _base(num, b) for base in range(2, 11)}

将生成 base : representation in that base 的字典。例如,如果 num = 23:

{2: '10111',
 3: '212',
 4: '113',
 5: '43',
 6: '35',
 7: '32',
 8: '27',
 9: '25',
 10: '23'}

试试这个

def rebase( value, new_base ):
    res = ""
    while value > 0:
      res = str( value % new_base ) + res
      value = int( value / new_base )
    return res