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

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

我是编码新手,正在 python 中解决代码战问题。任务是找到一个列表中第一个不连续的元素并return它([1,2,3,4,6,7,8,9]应该return6),如果它们都是连续的,return 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],将导致它尝试读取不存在的元素。