10
10
python binary_search.py
11
11
"""
12
12
from __future__ import print_function
13
+ import bisect
14
+
15
+
16
+ def assert_sorted (collection ):
17
+ """Check if collection is sorted. If not raises :py:class:`ValueError`
18
+
19
+ :param collection: collection
20
+ :return: True if collection is sorted
21
+ :raise: :py:class:`ValueError` if collection is not sorted
22
+
23
+ Examples:
24
+ >>> assert_sorted([0, 1, 2, 4])
25
+ True
26
+
27
+ >>> assert_sorted([10, -1, 5])
28
+ Traceback (most recent call last):
29
+ ...
30
+ ValueError: Collection must be sorted
31
+ """
32
+ if collection != sorted (collection ):
33
+ raise ValueError ('Collection must be sorted' )
34
+ return True
13
35
14
36
15
37
def binary_search (sorted_collection , item ):
16
- """Pure implementation of binary sort algorithm in Python
38
+ """Pure implementation of binary search algorithm in Python
17
39
18
40
:param sorted_collection: some sorted collection with comparable items
19
41
:param item: item value to search
@@ -36,8 +58,7 @@ def binary_search(sorted_collection, item):
36
58
...
37
59
ValueError: Collection must be sorted
38
60
"""
39
- if sorted_collection != sorted (sorted_collection ):
40
- raise ValueError ('Collection must be sorted' )
61
+ assert_sorted (sorted_collection )
41
62
left = 0
42
63
right = len (sorted_collection ) - 1
43
64
@@ -54,6 +75,37 @@ def binary_search(sorted_collection, item):
54
75
return None
55
76
56
77
78
+ def binary_search_std_lib (sorted_collection , item ):
79
+ """Pure implementation of binary search algorithm in Python using stdlib
80
+
81
+ :param sorted_collection: some sorted collection with comparable items
82
+ :param item: item value to search
83
+ :return: index of found item or None if item is not found
84
+
85
+ Examples:
86
+ >>> binary_search_std_lib([0, 5, 7, 10, 15], 0)
87
+ 0
88
+
89
+ >>> binary_search_std_lib([0, 5, 7, 10, 15], 15)
90
+ 4
91
+
92
+ >>> binary_search_std_lib([0, 5, 7, 10, 15], 5)
93
+ 1
94
+
95
+ >>> binary_search_std_lib([0, 5, 7, 10, 15], 6)
96
+
97
+ >>> binary_search_std_lib([5, 2, 1, 5], 2)
98
+ Traceback (most recent call last):
99
+ ...
100
+ ValueError: Collection must be sorted
101
+ """
102
+ assert_sorted (sorted_collection )
103
+ index = bisect .bisect_left (sorted_collection , item )
104
+ if index != len (sorted_collection ) and sorted_collection [index ] == item :
105
+ return index
106
+ return None
107
+
108
+
57
109
if __name__ == '__main__' :
58
110
import sys
59
111
# For python 2.x and 3.x compatibility: 3.x has not raw_input builtin
0 commit comments