I am trying to write a binary search that takes a sorted list and finds the largest number less than the target value:
def binary_max(list, target) hi=len(list)-1 lo=0 while lo<=hi: mid=(hi+lo)//2 midval=list[mid] if midval > target: hi=mid-1 elif midval <= target: lo=mid if hi==lo: break return(list[mid]) pass
however, when, for example, there is a list with a length of 2, hi = 1, and the average value will always get stuck on lo, is there anyway to avoid this problem?
thanks
source share