ホームページ >バックエンド開発 >Python チュートリアル >Python の二分探索および二分化モジュール
Python のリストの内部実装は配列であり、これは線形リストです。リスト内の要素を検索するには、時間計算量が O(n) の list.index() メソッドを使用できます。大量のデータの場合、二分探索を最適化に使用できます。二分探索ではオブジェクトを順序付けする必要があり、その基本原則は次のとおりです:
1. 配列の中央の要素が検索対象の要素である場合、検索プロセスは終了します。
2. 特定の要素が中央の要素より大きいか小さい場合、中央の要素より大きいか小さい配列の半分を検索し、以前と同様に中央の要素から比較を開始します。 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次に、これら 2 つの実装でパフォーマンス テストを実行します:
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()実行結果は次のとおりです:
Recursion: 3.12596702576 Loop: 2.08254289627ループ メソッドがより優れていることがわかります。再帰より効率的です。 Python には、順序付きリストを維持するための bisect モジュールがあります。 bisect モジュールは、順序付きリストに要素を挿入するためのアルゴリズムを実装します。場合によっては、リストを繰り返し並べ替えたり、大きなリストを作成して並べ替えたりするよりも効率的です。 Bisect は二等分を意味します。ここでは bisection メソッドを使用して並べ替えます。これにより、順序付きリストの適切な位置に要素が挿入され、順序付きリストを維持するために毎回 sort を呼び出す必要がなくなります。 以下は簡単な使用例です:
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出力結果:
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]Bisect モジュールによって提供される関数は次のとおりです: bisect.bisect_left(a,x, lo=0, hi=len(a)) : 順序付きリスト a に x が挿入されるインデックスを見つけます。 lo と hi はリストの範囲を指定するために使用され、デフォルトではリスト全体が使用されます。 x がすでに存在する場合は、それを左側に挿入します。戻り値はインデックスです。 bisect.bisect_right(a,x, lo=0, hi=len(a))bisect.bisect(a, x,lo=0, hi=len(a)) :これら 2 つの合計関数 bisect_left 同様ですが、x がすでに存在する場合は、それを右側に挿入します。 bisect.insort_left(a,x, lo=0, hi=len(a)): 順序付きリスト a に x を挿入します。効果は a.insert(bisect.bisect_left(a,x, lo, hi), x) と同じです。 bisect.insort_right(a,x, lo=0, hi=len(a))bisect.insort(a, x,lo=0, hi=len(a)) : insort_left と似ていますが、 x がすでに存在する場合は、右側に挿入します。 Bisect モジュールが提供する関数は 2 つのカテゴリに分類できます。bisect* はインデックスを見つけるためにのみ使用され、実際の挿入は実行しません。一方、insort* は実際の挿入に使用されます。このモジュールの一般的なアプリケーションは、スコア レベルを計算することです:
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']同様に、bisect モジュールを使用して二分探索を実装できます:
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ループ実装よりわずかに高速で、再帰実装よりもほぼ半分高速であることがわかります。 Pythonの有名なデータ処理ライブラリnumpyにも二分探索用の関数numpy.searchsortedがあり、使い方は基本的にbisectと同じですが、右側に挿入したい場合はパラメータside='right'を設定する必要があります。例:
>>> 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 loopnumpy.searchsorted の効率は非常に低く、bisect とは桁違いであることがわかります。したがって、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 loopnumpy.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])