python是否提供在排序列表上执行二进制搜索的功能,类似于C ++标准库的std::lower_bound
和std::upper_bound
算法?
答案 0 :(得分:15)
这些功能位于bisect模块中:
bisect。 bisect_left ( a , x , lo = 0 , hi = len(a))是std::lower_bound()
的模拟。
bisect。 bisect_right ( a , x , lo = 0 , hi = len(a))是std::upper_bound()
的模拟。
注意:还有一个函数 bisect (),它是 bisect_right ()的别名。
答案 1 :(得分:-2)
upper_bound(x) 应该给出 x 的最右边位置(如果 x 存在或 x 的下一个值的位置。
lower_bound(x) 应该给出 x 最左边的位置,如果 x 存在或者 x 的前一个值的位置
但是 bisect 模块没有为上界和下界函数构建。
bisect_left(x) 给出 x 最左边的位置(如果 x 存在)或 x 先前值的位置。
bisect_right(x) 给出下一个 x 值的位置