简体   繁体   English

isPalindrome 递归字符串

[英]isPalindrome recursion string

why does this not work?为什么这不起作用? It works for False palindrome;它适用于假回文; however, for anything True it never returns True.. I don't understand why this function does not return True?但是,对于任何 True 它永远不会返回 True .. 我不明白为什么这个 function 不返回 True? And how I should improve this same answer so that it returns True.以及我应该如何改进这个相同的答案,使其返回 True。

My logic was that after the function completes iterating through the entire string, it will return True.我的逻辑是,在 function 完成对整个字符串的迭代之后,它将返回 True。

def isPalindrome(string, i = 0):
    if i == len(string): 
        return True
    if string[i] != string[len(string)-1-i]:
        return False
    isPalindrome(string,i+1)

Problem is with your last line:问题出在你的最后一行:

isPalindrome(string,i+1)

That last line will eventually resolve to either True or False -- but how is that value being returned?最后一行最终将解析为TrueFalse —— 但是值是如何返回的呢? (It isn't.) (事实并非如此。)

Try:尝试:

return isPalindrome(string,i+1)

Check out the visualization here这里查看可视化

My hint would be check what you are returning (ie what does isPalindrome return).我的提示是检查您返回的内容(即 isPalindrome 返回的内容)。

If you want just the answer, it is here如果你只想要答案,它就在这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM