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?
thanks
Use temp variable and if statement to find the largest number in a list Python using for loop. Writing your own logic is easy, use temp variable to assign the first value of the list then swap it with the next large number.
In Python, there is a built-in function max() you can use to find the largest number in a list. To use it, call the max() on a list of numbers. It then returns the greatest number in that list.
Using all() function we can check if all values are less than any given value in a single line. It returns true if the given condition inside the all() function is true for all values, else it returns false.
The bisect
module provides functions to do exactly that. Use bisect.bisect.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With