forked from TheAlgorithms/Python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsolution.patch
More file actions
91 lines (87 loc) · 5.21 KB
/
Copy pathsolution.patch
File metadata and controls
91 lines (87 loc) · 5.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
diff --git a/searches/simple_binary_search.py b/searches/simple_binary_search.py
index 00e83ff9..895434d7 100644
--- a/searches/simple_binary_search.py
+++ b/searches/simple_binary_search.py
@@ -11,50 +11,61 @@ python3 simple_binary_search.py
from __future__ import annotations
-def binary_search(a_list: list[int], item: int) -> bool:
+def binary_search(a_list: list[int], item: int) -> int:
"""
+ Returns the leftmost index of `item` in `a_list` if found,
+ otherwise returns -1.
+
>>> test_list = [0, 1, 2, 8, 13, 17, 19, 32, 42]
>>> binary_search(test_list, 3)
- False
+ -1
>>> binary_search(test_list, 13)
- True
+ 4
>>> binary_search([4, 4, 5, 6, 7], 4)
- True
+ 0
>>> binary_search([4, 4, 5, 6, 7], -10)
- False
+ -1
>>> binary_search([-18, 2], -18)
- True
+ 0
>>> binary_search([5], 5)
- True
+ 0
>>> binary_search(['a', 'c', 'd'], 'c')
- True
+ 1
>>> binary_search(['a', 'c', 'd'], 'f')
- False
+ -1
>>> binary_search([], 1)
- False
+ -1
>>> binary_search([-.1, .1 , .8], .1)
- True
+ 1
>>> binary_search(range(-5000, 5000, 10), 80)
- True
+ 508
>>> binary_search(range(-5000, 5000, 10), 1255)
- False
+ -1
>>> binary_search(range(0, 10000, 5), 2)
- False
+ -1
"""
- if len(a_list) == 0:
- return False
- midpoint = len(a_list) // 2
- if a_list[midpoint] == item:
- return True
- if item < a_list[midpoint]:
- return binary_search(a_list[:midpoint], item)
- else:
- return binary_search(a_list[midpoint + 1 :], item)
+ low, high = 0, len(a_list) - 1
+ result = -1
+
+ while low <= high:
+ mid = (low + high) // 2
+ if a_list[mid] == item:
+ result = mid
+ high = mid - 1 # keep searching left for duplicates
+ elif item < a_list[mid]:
+ high = mid - 1
+ else:
+ low = mid + 1
+
+ return result
if __name__ == "__main__":
user_input = input("Enter numbers separated by comma:\n").strip()
sequence = [int(item.strip()) for item in user_input.split(",")]
target = int(input("Enter the number to be found in the list:\n").strip())
- not_str = "" if binary_search(sequence, target) else "not "
- print(f"{target} was {not_str}found in {sequence}")
+ index = binary_search(sequence, target)
+ if index != -1:
+ print(f"{target} found at index {index} in {sequence}")
+ else:
+ print(f"{target} was not found in {sequence}")