python - 通过另一个程序调用回文函数时输出错误

标签 python palindrome

我正在努力解决这个问题

A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.

下面是我用来判断一个数字是否为回文的代码。

 #largest product of two  digit no.s  which is a palindrome eg 91*99 = 9009
        def check_palindrome(str):
            x = len(str)
            for i in range(x//2):
                if str[i] == str[x-1-i]:
                    flag = 0
                else:
                    flag = 1
            if flag== 0:
                print "palindrome"
            else:
                print " not palindrome"
        check_palindrome('9009')
i= 91
j= 99
product = i* j
print product
check_palindrome('product')

当我在计算乘积后调用函数 check_palindrome() 时,程序给出了错误的输出,而当单独调用时它给出了正确的输出。

最佳答案

您将不是回文的文字 string "product" 传递给您的回文函数:

check_palindrome('product')

去除单引号并转换为字符串:

check_palindrome(str(product))

传递表示存储在 product 中的整数的字符串。


顺便说一句,这里有一个简单的方法来测试一个字符串是否是回文:

def check_palindrome(s):
    return s == s[::-1]

将字符串 s 的反向与自身进行比较。如果两者相等,则为回文。

关于python - 通过另一个程序调用回文函数时输出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48040562/

相关文章:

python - numpy+mkl 比 numpy 快吗?

python - 如何解决 jinja2.exceptions.TemplateSyntaxError?

python - 是否可以使用自定义方法/属性覆盖外键关系

python - 如何计算数据框列中 Spacy 的名词数量?

c - 调用函数时 char array[100] 和 char *array 之间的区别?

java - 在 Java 中获取用户输入

python - Project Euler #4 算法的可能优化

python - 如何正确运行 setup.py 文件?

java - 扫描并获取特定 token

java - 从两个三位数的乘积中优化最大的回文数?