Dec-01-2020, 05:45 PM
(Dec-01-2020, 04:51 PM)bowlofred Wrote:And what if my target is 100 and there is no 100 in the list, so I want to take the closest number to 100 that is smaller than 100?import bisect target = 100 sorted_list = [1, 2, 5, 6, 100, 102, 110, 140, 145] pos = bisect.bisect_left(sorted_list, target) # where to insert, so the number less than is to the left. # Beware of negative if you asked for a number less than any in the list print(f"Greatest number less than {target} is at position {pos-1} with value {sorted_list[pos-1]}")
Output:Greatest number less than 100 is at position 3 with value 6