Python中反向排序列表的二进制搜索
作者:互联网
如果使用bisect模块将列表以升序排序,则已经存在一个有关如何在Python中执行二进制搜索的主题:Binary search (bisection) in Python
有没有一种好的方法可以对反向排序的列表进行二进制搜索?
解决方法:
这就是documentations所说的:
Unlike the sorted() function, it does not make sense for the bisect() functions to have key or reversed arguments because that would lead to an inefficient design (successive calls to bisect functions would not “remember” all of the previous key lookups).
因此,它不支持自定义顺序.绕开它的任何尝试(例如两次反转列表或准备单独的键列表)都将花费线性时间,这完全破坏了二进制搜索的对数点.
这是接受比较器的二进制搜索的实现
def bisect(arr, val, cmp):
l = -1
r = len(arr)
while r - l > 1:
e = (l + r) >> 1
if cmp(arr[e], val): l = e
else: r = e
return r
它的行为类似于bisect_right,如果需要bisect_left,则在末尾返回l.这是反向数组的用法示例:
>>> a = [10**8 - x for x in range(10**8)]
>>> bisect(a, 100, lambda x, y: x > y)
99999900
标签:binary-search,python 来源: https://codeday.me/bug/20191120/2045262.html