Python:Palidrome(字符串索引超出范围)

 -cy-小衣橱 发布于 2023-02-12 17:50

我试着编写一个名为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 

有人可以告诉我里面有什么不对吗?

谢谢!!!

1 个回答
  • 对于你的代码,

    这条线:

    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表示必须从右侧(反向)解释字符串.所以我们检查字符串是否等于它的反向

    2023-02-12 17:52 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有