How to find the maximum quantity less than the target value in the list?

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

+6
source share
3 answers

The bisect module provides functions to do just that. Use bisect.bisect .

+2
source

Here is a simple function to do this. Hope it works:

 def bin_search(list, target): if target not in list: return None list.sort() return list[list.index(target)-1] 
+1
source

When you break out of the loop, mid still contains the value from the previous iteration.

0
source

Source: https://habr.com/ru/post/958215/


All Articles