[Python之路] bisect模块
bisect模块
bisect是Python提供的二分查找模块
源码如下:
"""Bisection algorithms.""" def insort_right(a, x, lo=0, hi=None): """Insert item x in list a, and keep it sorted assuming a is sorted. If x is already in a, insert it to the right of the rightmost x. 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 a.insert(lo, x) 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 def insort_left(a, x, lo=0, hi=None): """Insert item x in list a, and keep it sorted assuming a is sorted. If x is already in a, insert it to the left of the leftmost x. 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 a[mid] < x: lo = mid+1 else: hi = mid a.insert(lo, x) def bisect_left(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 before the leftmost 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 a[mid] < x: lo = mid+1 else: hi = mid return lo # Overwrite above definitions with a fast C implementation try: from _bisect import * except ImportError: pass # Create aliases bisect = bisect_right insort = insort_right
我们可以看到,bisect模块中一共只有4个函数:
insort_right(a, x, lo=0, hi=None) insort_left(a, x, lo=0, hi=None)
bisect_right(a, x, lo=0, hi=None)
bisect_left(a, x, lo=0, hi=None)
他们的区别是,insort要执行插入操作,而bisect不执行插入操作,只找到该插入的index。left和right的区别是,如果列表中已经存在该值,left表示插在其左边,right表示插在其右边。
参数:
a:列表
x:要插入的数
lo:列表开始索引,默认为0
hi:列表结束索引,默认为len(a)
源码在最后提供了两个函数别名:
# Create aliases bisect = bisect_right insort = insort_right
bisect默认是bisect_right,insort默认是insort_right。
保持学习,否则迟早要被淘汰*(^ 。 ^ )***