From b0a8634eef484b99e64f672cd83a9a6475216e07 Mon Sep 17 00:00:00 2001 From: shellhub Date: Fri, 18 Sep 2020 15:32:39 +0800 Subject: [PATCH 1/2] double linear search recursion --- searches/double_linear_search_recursion.py | 35 ++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 searches/double_linear_search_recursion.py diff --git a/searches/double_linear_search_recursion.py b/searches/double_linear_search_recursion.py new file mode 100644 index 000000000000..53fa941edc06 --- /dev/null +++ b/searches/double_linear_search_recursion.py @@ -0,0 +1,35 @@ +def search(list_data: list, key: int, left: int = 0, right: int = 0) -> int: + """ + Iterate through the array to find the index of key using recursion. + :param list_data: the list to be searched + :param key: the key to be searched + :param left: the index of first element + :param right: the index of last element + :return: the index of key value if found, -1 otherwise. + + >>> search(list(range(0, 11)), 5) + 5 + >>> search([1, 2, 4, 5, 3], 4) + 2 + >>> search([1, 2, 4, 5, 3], 6) + -1 + >>> search([5], 5) + 0 + >>> search([], 1) + -1 + """ + right = right or len(list_data) - 1 + if left > right: + return -1 + elif list_data[left] == key: + return left + elif list_data[right] == key: + return right + else: + return search(list_data, key, left + 1, right - 1) + + +if __name__ == '__main__': + import doctest + + doctest.testmod() From 6602cb3ff5933c2335ed045b58053731bd370233 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Fri, 18 Sep 2020 07:34:20 +0000 Subject: [PATCH 2/2] fixup! Format Python code with psf/black push --- searches/double_linear_search_recursion.py | 2 +- searches/simple_binary_search.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/searches/double_linear_search_recursion.py b/searches/double_linear_search_recursion.py index 53fa941edc06..1c483e974ca7 100644 --- a/searches/double_linear_search_recursion.py +++ b/searches/double_linear_search_recursion.py @@ -29,7 +29,7 @@ def search(list_data: list, key: int, left: int = 0, right: int = 0) -> int: return search(list_data, key, left + 1, right - 1) -if __name__ == '__main__': +if __name__ == "__main__": import doctest doctest.testmod() diff --git a/searches/simple_binary_search.py b/searches/simple_binary_search.py index 1d898e2d9ee0..b6215312fb2d 100644 --- a/searches/simple_binary_search.py +++ b/searches/simple_binary_search.py @@ -42,7 +42,7 @@ def binary_search(a_list: List[int], item: int) -> bool: if item < a_list[midpoint]: return binary_search(a_list[:midpoint], item) else: - return binary_search(a_list[midpoint + 1:], item) + return binary_search(a_list[midpoint + 1 :], item) if __name__ == "__main__":