I'm new to coding and am doing a codewars problem in 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. 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.
You can simply loop through and find the first element which isn't 1 larger than the previous element:
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.