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
pull/214/head
Christian Clauss 2021-04-16 14:45:36 +02:00 committed by GitHub
parent a22bea6fa6
commit efb642880d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 24 additions and 5 deletions

View File

@ -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: 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: if len(array) < 1:
return False return False
if len(array) == 1: if len(array) == 1:
return array[0] == target return array[0] == target
mid = len(array) // 2
if array[mid] < target: if array[mid] < target:
return binary_search(array[mid:], target) return binary_search(array[mid:], target)
elif array[mid] > target: elif array[mid] > target:
@ -12,7 +28,10 @@ def binary_search(array: list, target: int) -> bool:
else: else:
return True return True
if __name__ == "__main__": if __name__ == "__main__":
print(binary_search([1, 2, 3, 4, 5], 1)) for item in test_data:
print(binary_search([0, 4, 10, 1000], 10)) print(
print(binary_search([], -2)) f"binary_search({item.array}, {item.target}) is "
f"{binary_search(item.array, item.target)}"
)