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的dict。例如,如果num = 23:
我认为在标准库中没有任何一个函数可以做到这一点。但是为我自己的一个类处理a different project,我必须解决这类问题,我的解决方案如下:
(最后一个语句的不那么简洁的版本(扩展
for
循环)如下所示:在您的例子中,如果您只需要整数在各种基中的表示列表,那么代码将更简单:
将产生
base : representation in that base
的dict。例如,如果num = 23
:试试这个
这在NumPy到^{} 中提供:
结果:
相关问题 更多 >
编程相关推荐