Skip to main content
 首页 » 编程设计

Python 整数运算 : not all arguments converted during string formatting

2025年05月04日9oomusou

我刚刚编写了这个搜索素数回文(二进制和十进制)数的算法,但我得到了一个错误:

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() 

请您参考如下方法:

有时 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)