前言
其實Python 的列表(list)內部實作是一個數組,也就是線性表。在清單中尋找元素可以使用 list.index() 方法,其時間複雜度為O(n) 。對於大數據量,則可以用二分查找進行最佳化。
二分查找要求對象必須有序,其基本原理如下:
1.從數組的中間元素開始,如果中間元素正好是要查找的元素,則搜素過程結束;
特定元素大於或小於中間元素,則在數組大於或小於中間元素的那一半中查找,並且跟開始一樣從中間元素開始比較。
3.如果在某一步驟陣列為空,則代表找不到。
二分查找也成為折半查找,演算法每一次比較都使搜尋範圍縮小一半, 其時間複雜度為 O(logn)。
我們分別用遞歸和循環來實現二分查找:
def binary_search_recursion(lst, value, low, high): if high < low: return None mid = (low + high) / 2 if lst[mid] > value: return binary_search_recursion(lst, value, low, mid-1) elif lst[mid] < value: return binary_search_recursion(lst, value, mid+1, high) else: return mid def binary_search_loop(lst,value): low, high = 0, len(lst)-1 while low <= high: mid = (low + high) / 2 if lst[mid] < value: low = mid + 1 elif lst[mid] > value: high = mid - 1 else: return mid return None
接著對這兩種實作進行一下效能測試:
if __name__ == "__main__": import random lst = [random.randint(0, 10000) for _ in xrange(100000)] lst.sort() def test_recursion(): binary_search_recursion(lst, 999, 0, len(lst)-1) def test_loop(): binary_search_loop(lst, 999) import timeit t1 = timeit.Timer("test_recursion()", setup="from __main__ import test_recursion") t2 = timeit.Timer("test_loop()", setup="from __main__ import test_loop") print "Recursion:", t1.timeit() print "Loop:", t2.timeit()
做結果如下:rrrereee
效率高。 bisect 模組Python 有一個 bisect 模組,用於維護有序清單。 bisect 模組實作了一個演算法用於插入元素到有序列表。在某些情況下,這比反覆排序清單或建構一個大的清單再排序的效率更高。 Bisect 是二分法的意思,這裡使用二分法來排序,它會將一個元素插入到一個有序列表的合適位置,這使得不需要每次調用 sort 的方式維護有序列表。 下面是一個簡單的使用範例:Recursion: 3.12596702576 Loop: 2.08254289627
import bisect import random random.seed(1) print'New Pos Contents' print'--- --- --------' l = [] for i in range(1, 15): r = random.randint(1, 100) position = bisect.bisect(l, r) bisect.insort(l, r) print'%3d %3d' % (r, position), l
bisect.bisect(a, x,lo=0, hi=len(a)) :
這2個函數和bisect_left 類似,但如果x 已經存在,在其右邊插入。
在有序列表 a 中插入 x。和 a.insert(bisect.bisect_left(a,x, lo, hi), x) 的效果相同。
和insort_left 類似,但如果x 已經存在,在其右邊插入。
New Pos Contents --- --- -------- 14 0 [14] 85 1 [14, 85] 77 1 [14, 77, 85] 26 1 [14, 26, 77, 85] 50 2 [14, 26, 50, 77, 85] 45 2 [14, 26, 45, 50, 77, 85] 66 4 [14, 26, 45, 50, 66, 77, 85] 79 6 [14, 26, 45, 50, 66, 77, 79, 85] 10 0 [10, 14, 26, 45, 50, 66, 77, 79, 85] 3 0 [3, 10, 14, 26, 45, 50, 66, 77, 79, 85] 84 9 [3, 10, 14, 26, 45, 50, 66, 77, 79, 84, 85] 44 4 [3, 10, 14, 26, 44, 45, 50, 66, 77, 79, 84, 85] 77 9 [3, 10, 14, 26, 44, 45, 50, 66, 77, 77, 79, 84, 85] 1 0 [1, 3, 10, 14, 26, 44, 45, 50, 66, 77, 77, 79, 84, 85]
def grade(score,breakpoints=[60, 70, 80, 90], grades='FDCBA'): i = bisect.bisect(breakpoints, score) return grades[i] print [grade(score) for score in [33, 99, 77, 70, 89, 90, 100]]
['F', 'A', 'C', 'C', 'B', 'A', 'A']
def binary_search_bisect(lst, x): from bisect import bisect_left i = bisect_left(lst, x) if i != len(lst) and lst[i] == x: return i return None
Recursion: 4.00940990448 Loop: 2.6583480835 Bisect: 1.74922895432
>>> import numpy as np >>> from bisect import bisect_left, bisect_right >>> data = [2, 4, 7, 9] >>> bisect_left(data, 4) 1 >>> np.searchsorted(data, 4) 1 >>> bisect_right(data, 4) 2 >>> np.searchsorted(data, 4, side='right') 2
循環實現的二分查找的效能:
In [20]: %timeit -n 100 bisect_left(data, 99999) 100 loops, best of 3: 670 ns per loop In [21]: %timeit -n 100 np.searchsorted(data, 99999) 100 loops, best of 3: 56.9 ms per loop In [22]: %timeit -n 100 bisect_left(data, 8888) 100 loops, best of 3: 961 ns per loop In [23]: %timeit -n 100 np.searchsorted(data, 8888) 100 loops, best of 3: 57.6 ms per loop In [24]: %timeit -n 100 bisect_left(data, 777777) 100 loops, best of 3: 670 ns per loop In [25]: %timeit -n 100 np.searchsorted(data, 777777) 100 loops, best of 3: 58.4 ms per loop
可以看到其比循環實現略快,比遞歸實現差不多要快一半。
Python 著名的資料處理庫numpy 也有一個用於二分查找的函數 numpy.searchsorted, 用法與bisect 基本上相同,只不過如果要右邊插入時,需要設定參數side='right',例如:
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
那麼,我們再來比較一下性能:
>>> 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])
可以發現 numpy.searchsorted 效率是很低的,跟bisect 根本不在一個數量級上。因此searchsorted 不適合用來搜尋普通的陣列,但是它用來搜尋 numpy.ndarray 是相當快速的:
rrreeenumpy.searchsorted 可以同時搜尋多個值:
rrreee🎜🎜🎜篇文章的全部內容了,希望本文的內容對大家學習或使用python能有一定的幫助,如果有疑問大家可以留言交流。 🎜🎜更多Python實現二分查找與bisect模組詳解相關文章請關注PHP中文網! 🎜