我只是编写这个搜索素数回文(二进制和十进制)数字的算法,但是我收到了一个错误:
Traceback (most recent call last):
File "python", line 25, in <module>
File "python", line 10, in isPalindromic
TypeError: not all arguments converted during string formatting"
我无法理解我的错在哪里。此外,我不确定这是否有效,但对我来说(我是编程新手)听起来很合理。
import math
def isPalindromic():
n = 10
while True:
for i in range(3, int(math.sqrt(n)) + 1):
if n % i != 0:
n = str(n)
new_number = n[::-1]
if n == new_number:
n = int(n)
binary = str(bin(n)[2:])
binary_new = binary[::-1]
if binary == binary_new:
return n
n = int(n)
n = n + 1
a = isPalindromic()
答案 0 :(得分:4)
在n = int(n)
的情况下,在for循环中添加n != new_number
。因为在这种情况下n = str(n)
因此是字符串,所以n % i
被视为字符串格式化操作。由于n
不包含任何格式的derectives,因此您收到了错误。
答案 1 :(得分:4)
有时n
是int
,有时它是string
。如果是字符串,则%
是格式化运算符。
对两者使用一个变量肯定会让你遇到麻烦。
此外,您的代码可以清理很多。
import math
def is_palindrome(s):
return s == s[::-1]
def is_prime_dual_palindromic(n):
return all(n % i for i in range(2, int(math.sqrt(n)) + 1)) \
and is_palindrome(str(n)) \
and is_palindrome(bin(n)[2:])
a = is_prime_dual_palindromic(10)
答案 2 :(得分:2)
只需更改此行:
if n % i != 0:
对此:
if int(n) % i != 0:
问题是你在字符串上使用%
运算符,而不是int。这意味着您将获得字符串格式化运算符,而不是获取模数运算符。有关Python中%
的更多信息,请查看here。