I am trying to find a fixed point in an array using a function that only accepts one input (an array). The problem is, I'm trying to avoid building another function that this function can call. If I could do that, this situation would be solved. These arrays will contain a list of sorted integers for me to iterate through. I am trying to keep its runtime low by using binary search. I've tried this a 100 different ways, and nothing is quite working.
def fixed_point(a):
if len(a) <= 2: # tried len(a) == 0 and len(a) == 1
return -1
mid = len(a)//2 # have used (len(a)-1)//2 as well
if mid == a[mid]:
return a[mid]
if mid > a[mid]:
return find_point(a[mid+1:])
else:
return find_point(a[:mid])
return -1
This function will return -1 if no fixed point is found.
This function also passes 10000 tests built for this, but for some reason cannot find that "5" is the fixed point of array: [-10, -5, -2, 2, 3, 5, 7, 10, 15, 25, 35, 78, 129]
Curious as to what people might find wrong with this code.
midthat you're looking for is the midpoint with respect to the original array, right? When you slice the list and pass it in for the next call, the size changes so none of your if conditions are going to hold true after, because the mid you're looking for, and the mid you end up comparing will not be the same.