我试着编写一个名为is_palidrome_v3(s)的方法来比较单词的第一个和最后一个字母,然后是第二个和最后一个字母,直到该对不相同,最后检查索引是否> = len(s)// 2
def is_palidrome_v3(s): ''' (str) -> bool Return True if and only if s is a palidrome. >>> is_palidrome_v3('noon') True >>> is_palidrome_v3('racecar') True >>> is_palidrome_v3('dented') False ''' i = 0 while i <= len(s) // 2 and s[i] == s[len(s) - i]: i = i + 1 return i >= len(s)//2
但是当我运行它时:
is_palidrome_v3('noon')
有一个错误:
Traceback (most recent call last): File "", line 1, in is_palidrome_v3('noon') File "C:\Users\James\Google-h0925473\Learning Programming\Python\Python Fundamental (Coursera)\is_palidrome_v1.py", line 67, in is_palidrome_v3 while i <= len(s) // 2 and s[i] == s[len(s) - i]: IndexError: string index out of range
有人可以告诉我里面有什么不对吗?
谢谢!!!
对于你的代码,
这条线:
while i<=len(s)//2 and s[i] == s[len(s)-i]
是问题.在第一次迭代中,条件是:
while 0<=len(s)//2 and s[0] == s[len(s)]
并且索引len(s)
无法存在于字符串中.因此错误.将其更改为:
while i<len(s)//2 and s[0] == s[len(s)-i-1]:
这样可以解决问题
为什么要这么大惊小怪呢?
结帐这个很酷的方式:
if s == s[::-1]: return True return False
s [:: - 1]第一个:
说我们必须从头开始迭代.第二个:
说迭代直到结束.所以,::
通常意味着我们必须遍历整个字符串.最后的-1表示必须从右侧(反向)解释字符串.所以我们检查字符串是否等于它的反向