Jon*_*mer 2 python string recursion palindrome
好的,所以我试图创建一个递归函数,如果函数是回文,则返回True,否则返回False.但是,它没有走到最后,随机停止.
码:
def is_palindrome(word):
if len(word) == 1 or len(word) == 0:
return True
else:
lst = len(word) - 1
if word[0] == word[lst]:
print(len(word), " --> ", word)
print(word[0], " # ", word[lst])
is_palindrome(word[0+1:lst])
else:
return False
Run Code Online (Sandbox Code Playgroud)
对于我的生活,我无法弄清楚为什么.这是一个示例输出:
7 --> racecar
r # r
5 --> aceca
a # a
3 --> cec
c # c
^ It stops right here. Why doesn't it continue and return True when length = 1?
Run Code Online (Sandbox Code Playgroud)
您需要将调用返回到递归函数:
def is_palindrome(word):
if len(word) == 1 or len(word) == 0:
return True
else:
lst = len(word) - 1
if word[0] == word[lst]:
print(len(word), " --> ", word)
print(word[0], " # ", word[lst])
return is_palindrome(word[0+1:lst]) # change here
else:
return False
Run Code Online (Sandbox Code Playgroud)
您编码的原因似乎是在递归的最后一步停止是因为在这种情况下您实际上永远不会返回值.在某些编程语言中,例如C或Java,这些代码甚至都不能编译.Python似乎可以容忍它,但它会导致您当前的行为.