From efb642880de0384ef4234968989f1dd609b46ecb Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Fri, 16 Apr 2021 14:45:36 +0200 Subject: [PATCH] Add Python doctests to binary search (#193) * Add Python doctests to binary search * Add Python doctests to binary search * Rename searching/python/binary-search.py to algorithms/Python/searching/binary-search.py * Rename binary-search.py to binary_search.py --- algorithms/Python/searching/binary_search.py | 29 ++++++++++++++++---- 1 file changed, 24 insertions(+), 5 deletions(-) diff --git a/algorithms/Python/searching/binary_search.py b/algorithms/Python/searching/binary_search.py index 6e15a22f..b8f8ee19 100644 --- a/algorithms/Python/searching/binary_search.py +++ b/algorithms/Python/searching/binary_search.py @@ -1,10 +1,26 @@ +from collections import namedtuple + +TestData = namedtuple("TestData", "array target expected") + +test_data = ( + TestData([1, 2, 3, 4, 5], 1, True), + TestData([0, 4, 10, 1000], 10, True), + TestData([], -2, False), +) + + def binary_search(array: list, target: int) -> bool: - """ searches through a sorted list to find a target integer """ - mid = len(array) // 2 + """ + Search a sorted list to find a target integer + + >>> all(binary_search(x.array, x.target) == x.expected for x in test_data) + True + """ if len(array) < 1: return False if len(array) == 1: return array[0] == target + mid = len(array) // 2 if array[mid] < target: return binary_search(array[mid:], target) elif array[mid] > target: @@ -12,7 +28,10 @@ def binary_search(array: list, target: int) -> bool: else: return True + if __name__ == "__main__": - print(binary_search([1, 2, 3, 4, 5], 1)) - print(binary_search([0, 4, 10, 1000], 10)) - print(binary_search([], -2)) + for item in test_data: + print( + f"binary_search({item.array}, {item.target}) is " + f"{binary_search(item.array, item.target)}" + )