Bisect, is it possible to work with descending sorted lists?

前端 未结 10 720
旧巷少年郎
旧巷少年郎 2020-12-09 15:37

How can I use bisect module on lists that are sorted descending? e.g.

import bisect

x = [1.0,2.0,3.0,4.0] # normal, ascending
bisect.insort(x,2.5)  # -->         


        
10条回答
  •  隐瞒了意图╮
    2020-12-09 16:28

    Slightly updated bisect library code:

    def reverse_bisect_right(a, x, lo=0, hi=None):
        """Return the index where to insert item x in list a, assuming a is sorted in descending order.
    
        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.
    
        Essentially, the function returns number of elements in a which are >= than x.
        >>> a = [8, 6, 5, 4, 2]
        >>> reverse_bisect_right(a, 5)
        3
        >>> a[:reverse_bisect_right(a, 5)]
        [8, 6, 5]
        """
        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
    

提交回复
热议问题