正在获取 IndexError:字符串索引超出范围 -Python

如何解决正在获取 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 情况,当我们递归地将输入减少到一个字母或更少;处理我们递归调用的结果——一个常见的递归初学者错误。

因为这不是一个固有的数学问题,所以我倾向于从解决方案中去除数字和数学运算符。我还将参数视为一个序列,而不是一个字符串,以允许字符 strlist 之间的流畅转换:

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)) 
,

递归是一种函数式遗产,因此将其与函数式风格结合使用会产生最佳效果。这意味着避免诸如突变、变量重新分配和其他副作用之类的事情 -

  1. 如果输入字符串 s 少于 2 个字符,我们总是有一个回文。返回 true。
  2. (归纳)s 是 2 个字符或更多。如果第一个字符与最后一个字符不匹配,则返回 false
  3. (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 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-