1. 程式人生 > >bisect 二分查找

bisect 二分查找

too 可見 有一個 兩個 code could 位置 mage 列表

先說明的是,使用這個模塊的函數前先確保操作的列表是已排序的。

技術分享圖片

先看看 insort 函數:

技術分享圖片

其插入的結果是不會影響原有的排序。

再看看 bisect 函數:

技術分享圖片

其目的在於查找該數值將會插入的位置並返回,而不會插入。

接著看 bisect_left 和 bisect_right 函數,該函數用入處理將會插入重復數值的情況,返回將會插入的位置

Python 著名的數據處理庫 numpy 也有一個用於二分查找的函數 numpy.searchsorted, 用法與 bisect 基本相同,只不過如果要右邊插入時,需要設置參數 side=‘right‘

,例如:

searchsorted 不適合用於搜索普通的數組,但是它用來搜索 numpy.ndarray 是相當快的:

In [30]: data_ndarray = np.arange(0, 1000000)
 
In [31]: %timeit np.searchsorted(data_ndarray, 99999)
The slowest run took 16.04 times longer than the fastest. This could mean that an intermediate result is being cached.
1000000 loops, best of 3: 996 ns per loop
 
In [32]: %timeit np.searchsorted(data_ndarray, 8888) The slowest run took 18.22 times longer than the fastest. This could mean that an intermediate result is being cached. 1000000 loops, best of 3: 994 ns per loop In [33]: %timeit np.searchsorted(data_ndarray, 777777) The slowest run took 31.32 times longer than the fastest. This could mean that an intermediate result is being cached.
1000000 loops, best of 3: 990 ns per loop

numpy.searchsorted 可以同時搜索多個值:

>>> np.searchsorted([1,2,3,4,5], 3)
2
>>> np.searchsorted([1,2,3,4,5], 3, side=‘right‘)
3
>>> np.searchsorted([1,2,3,4,5], [-10, 10, 2, 3])
array([0, 5, 1, 2])

技術分享圖片

其對應的插入函數是 insort_left 和 insort_right :

技術分享圖片

可見,單純看其結果的話,兩個函數的操作結果是一樣的,其實插入的位置不同而已。

bisect 二分查找