首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >有快速Python函数将数字转换成不同的基吗?

有快速Python函数将数字转换成不同的基吗?
EN

Stack Overflow用户
提问于 2019-07-10 16:30:57
回答 3查看 89关注 0票数 0

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

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

代码语言:javascript
运行
复制
baseChars="0123456789"
def toBase(n, b): 
    return "0" if not n else toBase(n//b, b).lstrip("0") + baseChars[n%b]

我期望toBase函数返回所有基数从2-10表示的数字。我想避免NumPy

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2019-07-10 16:50:37

我认为在标准库中没有任何一个函数可以做到这一点。但是在为我自己的一个类编写一个不同的项目时,我必须解决这类问题,我的解决方案如下所示:

代码语言:javascript
运行
复制
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循环)的一个不那么简洁的版本如下所示):

代码语言:javascript
运行
复制
r = []
for i in bases:
    b = _base(num, i)
    if b == b[::-1]:
        r.append(i)
return r

在您的情况下,如果您只想要一个以不同基表示整数的列表,那么代码就会更简单:

代码语言:javascript
运行
复制
reps = {b: _base(num, b) for base in range(2, 11)}

会产生一个base : representation in that base的片段。例如,如果num = 23

代码语言:javascript
运行
复制
{2: '10111',
 3: '212',
 4: '113',
 5: '43',
 6: '35',
 7: '32',
 8: '27',
 9: '25',
 10: '23'}
票数 0
EN

Stack Overflow用户

发布于 2019-07-10 16:38:02

这在NumPy中可以通过base_repr()获得。

代码语言:javascript
运行
复制
import numpy as np
[np.base_repr(100, base) for base in range(2,11)]

结果:

代码语言:javascript
运行
复制
['1100100', '10201', '1210', '400', '244', '202', '144', '121', '100']
票数 1
EN

Stack Overflow用户

发布于 2019-07-10 17:20:04

尝尝这个

代码语言:javascript
运行
复制
def rebase( value, new_base ):
    res = ""
    while value > 0:
      res = str( value % new_base ) + res
      value = int( value / new_base )
    return res
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56975024

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档