A pure Python implementation of a recursive linear search algorithm :param sequence: a collection with comparable items (as sorted items not required in Linear Search) :param low: Lower bound of the array :param high: Higher bound of the array :param target: The element
(sequence: list, low: int, high: int, target: int)
| 34 | |
| 35 | |
| 36 | def rec_linear_search(sequence: list, low: int, high: int, target: int) -> int: |
| 37 | """ |
| 38 | A pure Python implementation of a recursive linear search algorithm |
| 39 | |
| 40 | :param sequence: a collection with comparable items (as sorted items not required |
| 41 | in Linear Search) |
| 42 | :param low: Lower bound of the array |
| 43 | :param high: Higher bound of the array |
| 44 | :param target: The element to be found |
| 45 | :return: Index of the key or -1 if key not found |
| 46 | |
| 47 | Examples: |
| 48 | >>> rec_linear_search([0, 30, 500, 100, 700], 0, 4, 0) |
| 49 | 0 |
| 50 | >>> rec_linear_search([0, 30, 500, 100, 700], 0, 4, 700) |
| 51 | 4 |
| 52 | >>> rec_linear_search([0, 30, 500, 100, 700], 0, 4, 30) |
| 53 | 1 |
| 54 | >>> rec_linear_search([0, 30, 500, 100, 700], 0, 4, -6) |
| 55 | -1 |
| 56 | """ |
| 57 | if not (0 <= high < len(sequence) and 0 <= low < len(sequence)): |
| 58 | raise Exception("Invalid upper or lower bound!") |
| 59 | if high < low: |
| 60 | return -1 |
| 61 | if sequence[low] == target: |
| 62 | return low |
| 63 | if sequence[high] == target: |
| 64 | return high |
| 65 | return rec_linear_search(sequence, low + 1, high - 1, target) |
| 66 | |
| 67 | |
| 68 | if __name__ == "__main__": |
nothing calls this directly
no outgoing calls
no test coverage detected