update:果然是思而不学则殆,今天了解到sortedcontainers.SortedList就可以满足绝大部分二分查找的需求。
Python的二分查找library只有针对indexable的bisect,这东西很不通用。在functools日益强大的趋势下,Python没有个好用的二分查找库函数也是离谱。于是我们只好自己写一个。
from typing import Callable
def binary_search(cond: Callable[[int], bool], l: int, r: int) -> int:
""" search m within [l:r] that [l:m] satisfies cond but [m:r] not
"""
while l < r:
m = (l+r) // 2
if cond(m):
l = m + 1
else:
r = m
return l
平时可以复制粘贴使用简洁版:
def binary_search(cond, l, r):
""" search m within [l:r] that [l:m] satisfies cond but [m:r] not
"""
while l < r:
m = (l+r) // 2
if cond(m): l = m + 1
else: r = m
return l
用法:
nums = [0,1,2,3,4]
target = 2
binary_search(lambda i: nums[i]<=target, 0, len(nums)) # returns: 3