The code is giving the correct answer for all test cases except when I enter a list such as [1,2,3,4,5]. Then it shows:
IndexError: list index out of range.
Why is this happening? Shouldn't the else statement at the end take care of this?
def func(n):
my_list = n.split()
l = []
for i in my_list:
l.append(int(i))
if len(l)==0 or len(l)==1:
return None
for k in range(0, len(l)):
if l[k+1] >= l[k] + 2:
return l[k+1]
else:
return None
n = input()
print(func(n))
elseas in the question?k+1inl[k+1]in theifcondition is out of range anywaytry,catch, andexceptfor error handling.for k in range(0,len(l)), k will go from 0 to len(l)-1. This causes l[k+1] to get out of range inif l[k+1]>=l[k]+2:when k equals len(l)-1.returnafter either of the branches in theif/else. That's probably not really what you want, but you shouldn't be getting anIndexError. Please make sure this is a minimal reproducible example. If it's not reproducible with your code, it doesn't do us much good!