Python 回文递归函数

Python 回文递归函数,python,list,function,recursion,palindrome,Python,List,Function,Recursion,Palindrome,我试着写一个递归函数,它告诉我一个字符串是否是回文,但我得到的只是一个无限循环,我不知道问题出在哪里 def isPalindrome(S): listush=list(S) #listush=['a', 'b', 'n', 'n', 'b', 'a'] length=len(listush) #length=6 if length==0 or length==1: return S, "is a palindrome!" elif listush

我试着写一个递归函数,它告诉我一个字符串是否是回文,但我得到的只是一个无限循环,我不知道问题出在哪里

def isPalindrome(S):
    listush=list(S) #listush=['a', 'b', 'n', 'n', 'b', 'a']
    length=len(listush) #length=6
    if length==0 or length==1:
        return S, "is a palindrome!"
    elif listush[0]!=listush[-1]:
        return S, "is not a palindrome!"
    else:
        del listush[0]
        del listush[-1]
        return isPalindrome(S)

print isPalindrome("abnnba")

首先,正确缩进代码

其次,使用相同的参数再次调用函数。使用要从中删除的列表或从中删除的列表调用,并使用S参数递归。

如果执行printlistush,您可以看到列表从未更改。 对代码的以下修改有效:

def isPalindrome(testStr, orig=None):
    if orig is None:
        orig = testStr
    length = len(testStr) #length=6
    print(testStr)
    if length == 0 or length == 1:
        return orig, "is a palindrome!"
    elif testStr[0] != testStr[-1]:
       return orig, "is not a palindrome!"
    else:
        return isPalindrome(testStr[1:-1], orig)

print isPalindrome("abnnba")

没有必要创建一个列表。python字符串已经是可索引序列

更好的是,我们可以使用切片,让函数返回True和False,而不是带有文本的元组,通过所有这些,isAlindrome变成了一行:

def isPalindrome(S):
    return len(S) < 2 or (S[0] == S[-1] and isPalindrome(S[1:-2]))

print isPalindrome('A')
>>> True
print isPalindrome('AA')
>>> True
print isPalindrome('BAAB')
>>> True
print isPalindrome('ABAB')
>>> False

关于你的代码,我想说一些事情

您可以发送列表的一部分,省去了删除的麻烦 元素。 你不需要把它转换成一个列表,所有你需要的操作 在查找回文时,字符串支持回文。 在递归函数中返回S,这将是一个 空listor字符串,因为它正在减少每个递归。在里面 在递归情况下,我建议您只返回True或False 这里有一个例子

def isPalindrome(S):
    length=len(S)
    if length < 2:
        return True
    elif S[0] != S[-1]:
        return False
    else:
        return isPalindrome(S[1:length - 1])
就这么简单。

希望这有帮助

def ispalindromeword: 如果lenworddel listush[0]和listush[-1]不删除S中的字符,则该列表与S无关。将原始字符串传递给递归,而不删除前后字符。