Bisect是Python中的内置模块,它只包含为数不多的几个函数,用于在Python中提供二分搜索方法,注意二分搜索需在一个有序列表中执行。
1)bisect_left
(a, x, lo=0, hi=len(a))
在 a 中找到 x 合适的插入点以维持有序。参数 lo 和 hi 可以被用于确定需要考虑的子集;默认情况下整个列表都会被使用。如果 x 已经在 a 里存在,那么插入点会在已存在元素之前(也就是左边)。返回的插入点 i 可以将数组 a 分成两部分。左侧是 all(val < x for val in a[lo:i])
,右侧是 all(val >= x for val in a[i:hi])
。
import bisect
A = [-15, -9, 2, 90, 90, 100, 112, 112, 112, 150]
print(bisect.bisect_left(A, -9))
print(bisect.bisect_left(A, 90))
The bisect_left fuction finds index of the target element. In the event where there are duplicate entries satisfying the target ele