python - IndexError : list index out of range , while finding the first non-consecutive number in a list in python

标签 python error-handling exit-code

我是编码新手,正在python中进行Codewars问题。任务是在列表中找到第一个非连续元素并将其返回([1,2,3,4,6,7,8,9]应该返回6),如果它们都是连续的,则返回None。我已经对其进行了编码,以使其能够正确执行操作,并且我已经通过了所有测试,但由于我退出代码这样而无法完成:

Traceback (most recent call last):
   File "main.py", line 5, in <module>
      Test.assert_equals(first_non_consecutive([1,2,3,4,5,6,7,8]), None)
   File "/home/codewarrior/solution.py", line 5, in first_non_consecutive
      elif n + 1 == arr[n + 1]:
IndexError: list index out of range
我以前遇到过这个问题,这很烦人,因为大多数时候我的代码正确地执行了预期的工作,但是由于某种原因,这种情况会发生。
这是我的代码:
def first_non_consecutive(arr):
    for n in arr:
        if n + 1 not in arr:
            return n + 2
        elif n + 1 == arr[n + 1]:
            return
我该怎么办?

最佳答案

问题描述给出了提示:

By not consecutive we mean not exactly 1 larger than the previous element of the array.


您可以简单地遍历并找到比上一个元素大1的第一个元素:
def first_non_consecutive(arr):
    # start from 1 instead of 0 since the first element must be consecutive
    for i in range(1, len(arr)):
        # literally check if it's equal to the previous element plus one
        if arr[i] != arr[i - 1] + 1:
            return arr[i]
    # didn't find a match so return None
    # default return value is None so this line isn't technically needed
    return None
您以前的解决方案不起作用,因为n是数组中的值,而不是索引,并且您正尝试使用它对数组进行索引,这意味着值大于索引的数组(例如[100])将导致它尝试读取不存在的元素。

关于python - IndexError : list index out of range , while finding the first non-consecutive number in a list in python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65061308/

相关文章:

linux - system ("tar xzf DirName/tarFile.tar DirNameInsideTar/FileName") 在 perl 中失败并返回 -1

c++ - c 中的快速排序代码,64 位 Windows 机器上无法解释的行为

python - webdriver.get() 引发 TimeoutException

python - 在收到无效输入后,如何阻止程序跳转到其他if语句?

python - 为什么NMF和LDA算法中使用random_state参数?使用每次生成的随机主题有什么好处?

rest - 如何在接受不同的Accept header 值的REST端点中处理错误响应。

javascript - 我可以指定如何处理异步 javascript 库中的错误吗?

bash - 结合使用 bash 选项进行错误处理(例如 pipefail、errexit、inherit_errexit)

python - 从另一个列表中查找数字索引

python - 向后绘制日期 matplotlib/pandas