How to find the greatest value smaller than N inside sorted list using binary search in Python

1 Answer

0 votes
from bisect import bisect_left 
 
def binary_search(lst, n): 
    i = bisect_left(lst, n) 
    if i: 
        return i - 1
    else: 
        return -1
  
lst = [1, 2, 3, 3, 4, 6, 20, 40]
 
i = binary_search(lst, 7) 
if i == -1: 
    print("Not found") 
else: 
    print(lst[i]) 
 
  
  
  
  
'''
run:
  
6
  
'''

 



answered Apr 30, 2021 by avibootz
...