Py小郑 2022-03-26 16:21 采纳率: 96.6%
浏览 130
已结题

Python bisece使用困惑

img


难道bisect只能用于升序数组吗?为啥逆序数组会这样,我想实现在逆序数组中使用bisect,要怎么操作

  • 写回答

1条回答 默认 最新

  • ash062 2022-03-26 16:36
    关注

    找到源码,稍微改下就行吧(if x > a[mid]),这是源码

    def bisect_right(a, x, lo=0, hi=None):
        """Return the index where to insert item x in list a, assuming a is sorted.
    
        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(x) will
        insert just after the rightmost x already there.
    
        Optional args lo (default 0) and hi (default len(a)) bound the
        slice of a to be searched.
        """
    
        if lo < 0:
            raise ValueError('lo must be non-negative')
        if hi is None:
            hi = len(a)
        while lo < hi:
            mid = (lo+hi)//2
            if x < a[mid]: hi = mid
            else: lo = mid+1
        return lo
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 4月3日
  • 已采纳回答 3月26日
  • 创建了问题 3月26日