二元搜索-左等分和右等分,比较更灵活
bsearch的Python项目详细描述
b搜索
Python中的二进制搜索,具有更灵活的比较。
安装
pip install bsearch
用法
bisect_left
和bisect_right
与bisect库向后兼容。例如:
frombsearchimportbisect_lefta=[1,2,3,4,5]i=bisect_left(a,4)# returns 3
您可以使用key
选项搜索不同类型的数组
frombsearchimportbisect_lefta=[(1,100),(2,100),(5,200)]# using the first element of the tuple as the keyi=bisect_left(a,2,key=lambdax:x[0])# returns 1
要搜索降序列表,请使用包装器binary_search
,并提供一个运算符。这将返回最小的i
,以便op(a[i], v)
frombsearchimportbinary_searcha=[5,4,3,2]i=binary_search(a,4,op=lambdaab:a>=b)# returns 1