Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/326.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python中测试回文_Python_String_Palindrome_Splice - Fatal编程技术网

在Python中测试回文

在Python中测试回文,python,string,palindrome,splice,Python,String,Palindrome,Splice,我现在知道有更好的解决办法,但我不明白为什么我会得到这样的结果 import sys def isPalindrome(test): if len(test) == 1: return("Is a palindrome") else: if test[0] == test[-1]: isPalindrome(test[1:-1]) else: return("Not a palind

我现在知道有更好的解决办法,但我不明白为什么我会得到这样的结果

import sys

def isPalindrome(test):
    if len(test) == 1:
        return("Is a palindrome")
    else:
        if test[0] == test[-1]:
            isPalindrome(test[1:-1])
        else:
            return("Not a palindrome")        

print(isPalindrome(sys.argv[1]))

对于真正的回文,我得到“无”。当结果不是回文时,我会得到预期的“非回文”值。

更改为以下行:

return isPalindrome(test[1:-1])

必须返回一个值,否则返回的值为
None

你的问题:第七行应该是:

return isPalindrome(test[1:-1])
如果不返回,则调用函数,并且不返回任何值

另外,正如在其他帖子中提到的,偶数字符串也有问题,因此添加len(test)==0的条件。

  • 如果-->为真,则没有返回路径。当您从递归中返回时,您只会将“Isa回文”返回到与之相关的级别,但超出该级别,您将向主函数返回空字符串

  • 您没有考虑递归何时变成空字符串。因此,条件
    test[0]==test[-1]
    给出了一个
    ***索引器:字符串索引超出范围

这项工作:

    def isPalindrome(test):
        if (len(test) == 1 or len(test)==0):   
            return("Is a palindrome")

    else:
        print test[0] == test[-1]
        if test[0] == test[-1]:
            return isPalindrome(test[1:-1])
        else:
            print('Not')
            return("Not a palindrome")        

    print(isPalindrome("aa"))
另一项建议

 def isPalindrome (test):
        if test[0] != test[-1]: return ("It is NOT a Palindrome")
        if len(test) == 1: return ("It is a Palindrome")
        else:return test[0] == test[-1] and isPalindrome(test[1:-1])

顺便说一句,使用
s==s[:-1]
可以很容易地做到这一点,当传递字符串的长度为偶数时,您将得到一个
索引器。当len(test)==1时,您正在检查条件;如果len(test)=0怎么办?例如,对于单词abba,在第三个递归中,您将得到一个空字符串。如果len(test)==1或len(test)==0,则您的
if
语句可以检查这两种情况