【发布时间】:2017-07-17 23:55:54
【问题描述】:
有用信息:
有关如何对各种数据类型列表进行排序的信息,请参阅: How to sort (list/tuple) of lists/tuples?
.. 有关如何对排序列表执行二分查找的信息,请参阅:Binary search (bisection) in Python
我的问题:
如何巧妙地将二分搜索(或其他 log(n) 搜索算法)应用于某个数据类型的列表,其中键是数据类型本身的内部组件?为了简单起见,我们可以使用元组列表作为示例:
x = [("a", 1), ("b",2), ("c",3)]
binary_search(x, "b") # search for "b", should return 1
# note how we are NOT searching for ("b",2) yet we want ("b",2) returned anyways
为了进一步简化:我们只需要返回一个搜索结果,而不是多个如果例如 ("b",2) 和 ("b",3) 都存在。 p>
更好:
我们如何修改下面的简单代码来执行上述操作?
from bisect import bisect_left
def binary_search(a, x, lo=0, hi=None): # can't use a to specify default for hi
hi = hi if hi is not None else len(a) # hi defaults to len(a)
pos = bisect_left(a, x, lo, hi) # find insertion position
return (pos if pos != hi and a[pos] == x else -1) # don't walk off the end
请注意:我不是在寻找完整的算法本身。相反,我正在寻找一些 Python 的标准(ish)库和/或 Python 的其他功能的应用程序,以便我可以随时轻松地搜索一些任意数据类型的排序列表。
谢谢
【问题讨论】:
标签: python algorithm list search