我是编码新手,正在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/