When are bisect_left and bisect_right not equal?

后端 未结 5 1290
半阙折子戏
半阙折子戏 2021-02-02 09:17

In my understanding, bisect_left and bisect_right are two different ways of doing the same thing: bisection, one coming from the left and the other coming from the right. Thus,

5条回答
  •  无人共我
    2021-02-02 09:43

    As the others have pointed out, bisect_left and bisect_right return different results when the element being looked up is present in the list.

    It turns out that bisect_left is more useful at hand, since it returns the exact index of the element being looked up if it is present in the list.

    >>> import bisect
    >>> bisect.bisect_left([1,2,3,4,5], 2)
    1
    

    Example of binary_search that uses bisect_left:

    from bisect import bisect_left
    
    def binsearch(l,e):
        '''
        Looks up element e in a sorted list l and returns False if not found.
        '''
        index = bisect_left(l,e)
        if index ==len(l) or l[index] != e:
            return False
        return index
    

    There will be a small change in the above code, if you want to use bisect_right instead of bisect_left and get the same result.

提交回复
热议问题