Py学习  »  Python

有没有一个快速的Python函数可以将数字转换成不同的基数?

MathWiz • 4 年前 • 734 次点击  

我正在写一个代码来检查一个数字以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函数返回2-10之间所有基数表示的数字。我想避开努比

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/53878
 
734 次点击  
文章 [ 3 ]  |  最新文章 4 年前
Stefan
Reply   •   1 楼
Stefan    4 年前

def rebase( value, new_base ):
    res = ""
    while value > 0:
      res = str( value % new_base ) + res
      value = int( value / new_base )
    return res
TomNash
Reply   •   2 楼
TomNash    4 年前

这在纽比到 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']
Green Cloak Guy
Reply   •   3 楼
Green Cloak Guy    4 年前

我认为在标准库中没有一个函数可以做到这一点。但正在努力 a different project 对于我自己的一门课,我必须解决这类问题,我的解决方案如下:

def _base(decimal, base):
    """
    Converts a number to the given base, returning a string.
    Taken from https://stackoverflow.com/a/26188870/2648811
    :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'}