如何解决正在获取 IndexError:字符串索引超出范围 -Python
def is_palindrome(x,pos_index,neg_index):
if x[pos_index] == x[neg_index]:
print("")
else:
return False
pos_index += 1
neg_index -= 1
is_palindrome(x,neg_index)
print(is_palindrome("racecar",-1))
解决方法
缺少您的最终条件。您每次都会调用该函数,因此您的 pos_index 变为 6 ('r')。之后,您应该停止,而是添加一个并再次启动该功能。所以你得到了一个超出范围的字符串索引。
请注意,对于您的下一个问题,一些补充信息或特定问题会很好。
,您收到错误的原因是因为 is_palindrome()
不断调用 is_palindrome()
,并且如果单词 是 回文,则不会停止。只有当词不是回文时,该函数才会返回。由于没有停止点,最终正负索引都会超过字符串的最大索引。我会尝试使用这个:
def is_palindrome(phrase):
phrase = "".join(phrase.lower().split())
index,imax = 0,len(phrase)-1
while index < imax-index:
if phrase[index] != phrase[imax-index]:
return False
index += 1
return True
请注意,这只检查直到 index
尽可能接近字符串的一半(可以通过将 print(index)
放入 while
循环中来观察)。这样,代码就不会“仔细检查”字符串的后半部分。
以下是一些测试运行:
>>> is_palindrome("racecar")
True
>>> is_palindrome("bus")
False
>>> is_palindrome("a man a plan a canal panama")
True
>>> is_palindrome("AABBAA")
True
然而,如果你想保持递归性质,你可以尝试使用这个:
def is_palindrome(phrase,positive=0,negative=-1):
phrase = ''.join(phrase.lower().split())
if positive >= len(phrase):
return True
if phrase[positive] == phrase[negative]:
return is_palindrome(phrase,positive+1,negative-1)
return False
一些测试运行:
>>> is_palindrome("racecar")
True
>>> is_palindrome("bus")
False
>>> is_palindrome("A man a plan a canal panama")
True
>>> is_palindrome("AABBAA")
True
,
如果我要修复您的代码并保留大部分代码,我会执行以下操作:
def is_palindrome_recursive(x,pos_index,neg_index):
if -neg_index >= len(x):
return True
if x[pos_index] != x[neg_index]:
return False
pos_index += 1
neg_index -= 1
return is_palindrome_recursive(x,neg_index)
def is_palindrome(string):
return is_palindrome_recursive(string,-1)
print(is_palindrome("racecar"))
主要变化是:一个额外的 return
情况,当我们递归地将输入减少到一个字母或更少;处理我们递归调用的结果——一个常见的递归初学者错误。
因为这不是一个固有的数学问题,所以我倾向于从解决方案中去除数字和数学运算符。我还将参数视为一个序列,而不是一个字符串,以允许字符 str
和 list
之间的流畅转换:
def is_palindrome(sequence):
if sequence:
first,*rest = sequence
if rest:
*middle,last = rest
if first != last:
return False
return is_palindrome(middle)
return True
if __name__ == "__main__":
print(is_palindrome("racecar"))
print(is_palindrome("radar"))
print(is_palindrome("ABBA"))
print(is_palindrome("pop"))
print(is_palindrome("cc"))
print(is_palindrome("I"))
print(is_palindrome(""))
我希望该问题的递归谓词函数具有三种return
可能性:return True
成功; return False
失败; return is_palindrome(...)
一个我还不知道的递归。
试试这个:
def is_palindrome(x,neg_index):
if x[pos_index] == x[neg_index]:
print("")
else:
return False
if pos_index==len(x)-1:
exit()
else:
pos_index += 1
neg_index -= 1
is_palindrome(x,neg_index)
print(is_palindrome("racecar",-1))
,
递归是一种函数式遗产,因此将其与函数式风格结合使用会产生最佳效果。这意味着避免诸如突变、变量重新分配和其他副作用之类的事情 -
- 如果输入字符串
s
少于 2 个字符,我们总是有一个回文。返回 true。 - (归纳)
s
是 2 个字符或更多。如果第一个字符与最后一个字符不匹配,则返回 false - (inductive)
s
为 2 个或更多字符且第一个字符与最后一个字符匹配。返回子问题的结果,s[1:-1]
def is_palindrome(s):
if len(s) < 2:
return True #1
elif s[0] != s[-1]:
return False #2
else:
return is_palindrome(s[1:-1]) #3
is_palindrome("racecar")
is_palindrome("aceca")
is_palindrome("cec")
is_palindrome("e")
True
我们可以将底部的两个逻辑分支合二为一-
def is_palindrome(s):
if len(s) < 2:
return True
else:
return s[0] == s[-1] and is_palindrome(s[1:-1])
最后我们可以完全折叠 if
并简单地对整个表达式使用逻辑运算符 -
def is_palindrome(s):
return len(s) < 2 or s[0] == s[-1] and is_palindrome(s[1:-1])
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。