Skip to content

Commit c1a56f5

Browse files
UmairKamrancclauss
andauthored
Chore: Added type hints to searches/binary_search.py (TheAlgorithms#2682)
* Chore: Added type hints to searches/binary_search.py * Use -1 as the sentinal value * Wrap long lines * Update binary_search.py * Update binary_search.py Co-authored-by: Christian Clauss <[email protected]>
1 parent 5423179 commit c1a56f5

File tree

1 file changed

+28
-46
lines changed

1 file changed

+28
-46
lines changed

Diff for: searches/binary_search.py

+28-46
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,21 @@
1+
#!/usr/bin/env python3
2+
13
"""
24
This is pure Python implementation of binary search algorithms
35
46
For doctests run following command:
5-
python -m doctest -v binary_search.py
6-
or
77
python3 -m doctest -v binary_search.py
88
99
For manual testing run:
10-
python binary_search.py
10+
python3 binary_search.py
1111
"""
1212
import bisect
13+
from typing import List, Optional
1314

1415

15-
def bisect_left(sorted_collection, item, lo=0, hi=None):
16+
def bisect_left(
17+
sorted_collection: List[int], item: int, lo: int = 0, hi: int = -1
18+
) -> int:
1619
"""
1720
Locates the first element in a sorted array that is larger or equal to a given
1821
value.
@@ -43,7 +46,7 @@ def bisect_left(sorted_collection, item, lo=0, hi=None):
4346
>>> bisect_left([0, 5, 7, 10, 15], 6, 2)
4447
2
4548
"""
46-
if hi is None:
49+
if hi < 0:
4750
hi = len(sorted_collection)
4851

4952
while lo < hi:
@@ -56,7 +59,9 @@ def bisect_left(sorted_collection, item, lo=0, hi=None):
5659
return lo
5760

5861

59-
def bisect_right(sorted_collection, item, lo=0, hi=None):
62+
def bisect_right(
63+
sorted_collection: List[int], item: int, lo: int = 0, hi: int = -1
64+
) -> int:
6065
"""
6166
Locates the first element in a sorted array that is larger than a given value.
6267
@@ -86,7 +91,7 @@ def bisect_right(sorted_collection, item, lo=0, hi=None):
8691
>>> bisect_right([0, 5, 7, 10, 15], 6, 2)
8792
2
8893
"""
89-
if hi is None:
94+
if hi < 0:
9095
hi = len(sorted_collection)
9196

9297
while lo < hi:
@@ -99,7 +104,9 @@ def bisect_right(sorted_collection, item, lo=0, hi=None):
99104
return lo
100105

101106

102-
def insort_left(sorted_collection, item, lo=0, hi=None):
107+
def insort_left(
108+
sorted_collection: List[int], item: int, lo: int = 0, hi: int = -1
109+
) -> None:
103110
"""
104111
Inserts a given value into a sorted array before other values with the same value.
105112
@@ -140,7 +147,9 @@ def insort_left(sorted_collection, item, lo=0, hi=None):
140147
sorted_collection.insert(bisect_left(sorted_collection, item, lo, hi), item)
141148

142149

143-
def insort_right(sorted_collection, item, lo=0, hi=None):
150+
def insort_right(
151+
sorted_collection: List[int], item: int, lo: int = 0, hi: int = -1
152+
) -> None:
144153
"""
145154
Inserts a given value into a sorted array after other values with the same value.
146155
@@ -181,7 +190,7 @@ def insort_right(sorted_collection, item, lo=0, hi=None):
181190
sorted_collection.insert(bisect_right(sorted_collection, item, lo, hi), item)
182191

183192

184-
def binary_search(sorted_collection, item):
193+
def binary_search(sorted_collection: List[int], item: int) -> Optional[int]:
185194
"""Pure implementation of binary search algorithm in Python
186195
187196
Be careful collection must be ascending sorted, otherwise result will be
@@ -219,7 +228,7 @@ def binary_search(sorted_collection, item):
219228
return None
220229

221230

222-
def binary_search_std_lib(sorted_collection, item):
231+
def binary_search_std_lib(sorted_collection: List[int], item: int) -> Optional[int]:
223232
"""Pure implementation of binary search algorithm in Python using stdlib
224233
225234
Be careful collection must be ascending sorted, otherwise result will be
@@ -248,7 +257,9 @@ def binary_search_std_lib(sorted_collection, item):
248257
return None
249258

250259

251-
def binary_search_by_recursion(sorted_collection, item, left, right):
260+
def binary_search_by_recursion(
261+
sorted_collection: List[int], item: int, left: int, right: int
262+
) -> Optional[int]:
252263

253264
"""Pure implementation of binary search algorithm in Python by recursion
254265
@@ -286,41 +297,12 @@ def binary_search_by_recursion(sorted_collection, item, left, right):
286297
return binary_search_by_recursion(sorted_collection, item, midpoint + 1, right)
287298

288299

289-
def __assert_sorted(collection):
290-
"""Check if collection is ascending sorted, if not - raises :py:class:`ValueError`
291-
292-
:param collection: collection
293-
:return: True if collection is ascending sorted
294-
:raise: :py:class:`ValueError` if collection is not ascending sorted
295-
296-
Examples:
297-
>>> __assert_sorted([0, 1, 2, 4])
298-
True
299-
300-
>>> __assert_sorted([10, -1, 5])
301-
Traceback (most recent call last):
302-
...
303-
ValueError: Collection must be ascending sorted
304-
"""
305-
if collection != sorted(collection):
306-
raise ValueError("Collection must be ascending sorted")
307-
return True
308-
309-
310300
if __name__ == "__main__":
311-
import sys
312-
313301
user_input = input("Enter numbers separated by comma:\n").strip()
314-
collection = [int(item) for item in user_input.split(",")]
315-
try:
316-
__assert_sorted(collection)
317-
except ValueError:
318-
sys.exit("Sequence must be ascending sorted to apply binary search")
319-
320-
target_input = input("Enter a single number to be found in the list:\n")
321-
target = int(target_input)
302+
collection = sorted(int(item) for item in user_input.split(","))
303+
target = int(input("Enter a single number to be found in the list:\n"))
322304
result = binary_search(collection, target)
323-
if result is not None:
324-
print(f"{target} found at positions: {result}")
305+
if result is None:
306+
print(f"{target} was not found in {collection}.")
325307
else:
326-
print("Not found")
308+
print(f"{target} was found at position {result} in {collection}.")

0 commit comments

Comments
 (0)