>>> is_palindrome("racecar")
True
>>> is_palindrome("bus")
False
>>> is_palindrome("a man a plan a canal panama")
True
>>> is_palindrome("AABBAA")
True
>>> is_palindrome("racecar")
True
>>> is_palindrome("bus")
False
>>> is_palindrome("A man a plan a canal panama")
True
>>> is_palindrome("AABBAA")
True
出现错误的原因是
is_palindrome()
连续调用is_palindrome()
,如果单词是回文,则不会停止。仅当单词不是回文时,函数才会返回。由于没有停止点,最终正索引和负索引都将超过字符串的最大索引。我会尝试使用这个:请注意,这只会检查直到
index
尽可能接近字符串的中间位置(这可以通过将print(index)
放入while
循环中来观察)。这样,代码就不会“双重检查”字符串的后半部分以下是一些测试运行:
但是,如果希望保留递归性质,可以尝试使用以下方法:
一些测试运行:
你的最终状态不见了。每次调用函数时,pos_索引变为6('r')。在此之后,您应该停止,但您可以添加一个,然后再次启动该函数。所以你得到了一个超出范围的字符串索引
还有一点注意,对于你的下一个问题,一些补充信息或一个特定的问题会很好
如果我要修复您的代码并保留大部分代码,我会执行以下操作:
其中主要的变化是:当我们递归地将输入减少到一个字母或更少时,增加了一个
return
情况;处理递归调用的结果——一个常见的递归初学者错误由于这不是一个固有的数学问题,我倾向于从解中得到数字和数学运算符。我还将把参数视为一个序列,而不是一个字符串,以允许在字符的
str
和list
之间进行流畅的转换:我希望这个问题的递归谓词函数有三种}
return
可能性:return True
成功^失败时{return is_palindrome(...)
一个递归,我还不知道相关问题 更多 >
编程相关推荐