Skip to content

Commit ec6b64a

Browse files
committed
Add bin search algorithm using stdlib
1 parent 65ca0bb commit ec6b64a

File tree

1 file changed

+55
-3
lines changed

1 file changed

+55
-3
lines changed

Diff for: binary_seach.py

+55-3
Original file line numberDiff line numberDiff line change
@@ -10,10 +10,32 @@
1010
python binary_search.py
1111
"""
1212
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
1335

1436

1537
def binary_search(sorted_collection, item):
16-
"""Pure implementation of binary sort algorithm in Python
38+
"""Pure implementation of binary search algorithm in Python
1739
1840
:param sorted_collection: some sorted collection with comparable items
1941
:param item: item value to search
@@ -36,8 +58,7 @@ def binary_search(sorted_collection, item):
3658
...
3759
ValueError: Collection must be sorted
3860
"""
39-
if sorted_collection != sorted(sorted_collection):
40-
raise ValueError('Collection must be sorted')
61+
assert_sorted(sorted_collection)
4162
left = 0
4263
right = len(sorted_collection) - 1
4364

@@ -54,6 +75,37 @@ def binary_search(sorted_collection, item):
5475
return None
5576

5677

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+
57109
if __name__ == '__main__':
58110
import sys
59111
# For python 2.x and 3.x compatibility: 3.x has not raw_input builtin

0 commit comments

Comments
 (0)