Pure implementation of a binary search algorithm in Python using stdlib Be careful collection must be ascending sorted otherwise, the result will be unpredictable :param sorted_collection: some ascending sorted collection with comparable items :param item: item value to search
(sorted_collection: list[int], item: int)
| 215 | |
| 216 | |
| 217 | def binary_search_std_lib(sorted_collection: list[int], item: int) -> int: |
| 218 | """Pure implementation of a binary search algorithm in Python using stdlib |
| 219 | |
| 220 | Be careful collection must be ascending sorted otherwise, the result will be |
| 221 | unpredictable |
| 222 | |
| 223 | :param sorted_collection: some ascending sorted collection with comparable items |
| 224 | :param item: item value to search |
| 225 | :return: index of the found item or -1 if the item is not found |
| 226 | |
| 227 | Examples: |
| 228 | >>> binary_search_std_lib([0, 5, 7, 10, 15], 0) |
| 229 | 0 |
| 230 | >>> binary_search_std_lib([0, 5, 7, 10, 15], 15) |
| 231 | 4 |
| 232 | >>> binary_search_std_lib([0, 5, 7, 10, 15], 5) |
| 233 | 1 |
| 234 | >>> binary_search_std_lib([0, 5, 7, 10, 15], 6) |
| 235 | -1 |
| 236 | """ |
| 237 | if list(sorted_collection) != sorted(sorted_collection): |
| 238 | raise ValueError("sorted_collection must be sorted in ascending order") |
| 239 | index = bisect.bisect_left(sorted_collection, item) |
| 240 | if index != len(sorted_collection) and sorted_collection[index] == item: |
| 241 | return index |
| 242 | return -1 |
| 243 | |
| 244 | |
| 245 | def binary_search_with_duplicates(sorted_collection: list[int], item: int) -> list[int]: |
nothing calls this directly
no outgoing calls
no test coverage detected