Pure implementation of binary search algorithm in Python using stdlib Be careful collection must be sorted, otherwise result will be unpredictable :param sorted_collection: some sorted collection with comparable items :param item: item value to search :return: index of found it
(sorted_collection, item)
| 58 | |
| 59 | |
| 60 | def binary_search_std_lib(sorted_collection, item): |
| 61 | """Pure implementation of binary search algorithm in Python using stdlib |
| 62 | |
| 63 | Be careful collection must be sorted, otherwise result will be |
| 64 | unpredictable |
| 65 | |
| 66 | :param sorted_collection: some sorted collection with comparable items |
| 67 | :param item: item value to search |
| 68 | :return: index of found item or None if item is not found |
| 69 | |
| 70 | Examples: |
| 71 | >>> binary_search_std_lib([0, 5, 7, 10, 15], 0) |
| 72 | 0 |
| 73 | |
| 74 | >>> binary_search_std_lib([0, 5, 7, 10, 15], 15) |
| 75 | 4 |
| 76 | |
| 77 | >>> binary_search_std_lib([0, 5, 7, 10, 15], 5) |
| 78 | 1 |
| 79 | |
| 80 | >>> binary_search_std_lib([0, 5, 7, 10, 15], 6) |
| 81 | |
| 82 | """ |
| 83 | index = bisect.bisect_left(sorted_collection, item) |
| 84 | if index != len(sorted_collection) and sorted_collection[index] == item: |
| 85 | return index |
| 86 | return None |
| 87 | |
| 88 | def binary_search_by_recursion(sorted_collection, item, left, right): |
| 89 |
nothing calls this directly
no outgoing calls
no test coverage detected