I am trying to write a binary search that takes a sorted list and finds the largest number less than a 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 length 2, hi=1
and the mid
value will always be stuck on lo
.
Is there anyway to avoid this problem?
while
loop is idiomatic in Python unless it is an infinite loop (while True
) – Lanthanumbisect.py
... – Seeing