I'm trying to do a recursive program in Python which returns the first index of a list which is equals to it's value, for example: [0, 1, 5, 6] returns 0. But when I pass the last list it returns 1, and I don't know why.
Code:
def index(list):
"""Returns the first index of the list where list[i] == i"""
return __auxindex(list, 0, len(list) - 1)
def __auxindex(list, start, end):
if start < end:
half = (start + end) // 2
if list[half] == half:
return half
elif list[half] > half:
return __auxindex(list, start, half)
else:
return __auxindex(list, half + 1, end)
else:
return start
list = input('Values (, ): ').split(', ')
list = [int(i) for i in list]
print(index(list))
EDIT: I forgot that the list has to be ordered. So this code works.