[英]IndexError: list index out of range , while finding the first non-consecutive number in a list in python
I'm new to coding and am doing a codewars problem in python.我是编码新手,正在 python 中处理代码战问题。 The task is to find the first non-consecutive element in a list and return it (
[1,2,3,4,6,7,8,9]
should return 6
), if they are all consecutive, return None.任务是在列表中找到第一个不连续的元素并将其返回(
[1,2,3,4,6,7,8,9]
应该返回6
),如果它们都是连续的,则返回 None。 I have coded it so that it does what it should correctly, and I have passed all the tests but cannot finish because I have exit code saying this:我已经对其进行了编码,以便它可以正确地完成它应该做的事情,并且我已经通过了所有测试但无法完成,因为我有退出代码这样说:
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
I have encountered this problem before and it's annoying because most of the time my code does what it's supposed to, correctly, but for some reason this happens.我以前遇到过这个问题,这很烦人,因为大多数时候我的代码正确地完成了它应该做的事情,但由于某种原因,这种情况发生了。
Here is my code:这是我的代码:
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
What do I do?我该怎么办?
The problem description gives a hint:问题描述给出了提示:
By not consecutive we mean not exactly 1 larger than the previous element of the array.
不连续是指不完全比数组的前一个元素大 1。
You can simply loop through and find the first element which isn't 1 larger than the previous element:您可以简单地循环并找到不比前一个元素大 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
Your previous solution doesn't work since n
is a value in the array, not an index, and you're trying to index the array with it, meaning that an array with values larger than the indices, such as [100]
, will cause it to try to read a non-existent element.您以前的解决方案不起作用,因为
n
是数组中的一个值,而不是索引,并且您试图用它来索引数组,这意味着值大于索引的数组,例如[100]
,将使其尝试读取不存在的元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.