Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the highest number less than target value in a list?

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

like image 654
user2906979 Avatar asked Nov 16 '13 19:11

user2906979


People also ask

How do you find the maximum number in a list using a loop?

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.

How do you find the highest number in a list Python?

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.

How do you check if a value is less than all values in a list Python?

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.


1 Answers

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

like image 172
shx2 Avatar answered Oct 15 '22 14:10

shx2