bisect python 好用的的数组二分算法

2022/4/4 1:20:14

本文主要是介绍bisect python 好用的的数组二分算法,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

bisect是python自带的标准库。

其中bisect_left是插入到左边,bisect_rightbisect是插入到右边

>>> a = [0, 1, 2, 3, 4]
>>> x = 2
>>> index = bisect.bisect(a,x)
>>> index
3
>>> a.insert(index,x)
>>> a
[0, 1, 2, 2, 3, 4]
def bisect_right(a, x, lo=0, hi=None, *, key=None):
    """Return the index where to insert item x in list a, assuming a is sorted.
    返回x项插入到列表a的下标,假设a是有序的
    
    The return value i is such that all e in a[:i] have e <= x, and all e in
    a[i:] have e > x.  So if x already appears in the list, a.insert(i, x) will
    insert just after the rightmost x already there.
    返回的值i使所有的在a[:i]范围中的e有e<= x,并且所有的在a[i:]范围中的e有e > x。所以如果x已经
    在列表中,a.insert(i, x)将会插入到已经有的x的最右边
    
    Optional args lo (default 0) and hi (default len(a)) bound the
    slice of a to be searched.
    可选参数 lo 默认0和hi默认为len(a) 使寻找的切片边界
    """

    if lo < 0:
        raise ValueError('lo must be non-negative')#lo 必须是非负
    if hi is None:
        hi = len(a)
    # Note, the comparison uses "<" to match the
    # __lt__() logic in list.sort() and in heapq.
    if key is None:
        while lo < hi:
            mid = (lo + hi) // 2
            if x < a[mid]:
                hi = mid
            else:
                lo = mid + 1
    else:
        while lo < hi:
            mid = (lo + hi) // 2
            if x < key(a[mid]):
                hi = mid
            else:
                lo = mid + 1
    return lo


这篇关于bisect python 好用的的数组二分算法的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程