Skip to content

Update linear_search.py #2422

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Sep 14, 2020
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Update linear_search.py
Both the functions return the index if the target is found and -1 if it is not found
The rec_linear_search raises an exception if there is an indexing problem
Made changes in the doc comments
  • Loading branch information
Ashley-J-George authored Sep 14, 2020
commit dbf677fd84d3a5c5e71b8c6a56cd59b995edcfc7
43 changes: 22 additions & 21 deletions searches/linear_search.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,47 +30,48 @@ def linear_search(sequence: list, target: int) -> int:
1

>>> linear_search([0, 5, 7, 10, 15], 6)

-1
"""
for index, item in enumerate(sequence):
if item == target:
return index
return None
return -1


def rec_linear_search(sequence: list, low: int, high: int, target: int) -> int:
'''
"""
Pure implementation of recursive linear search algorithm in Python

:param sequence: An array of items
: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 to be found
:return: Index of the key or -1 if key not found or None in case of an exception
:return: Index of the key or -1 if key not found

Examples:
>>> rec_linear_search([0, 30, 500, 100, 700], 0, 4, 0)
The element 0 is present at index 0
0

>>> rec_linear_search([0, 30, 500, 100, 700], 0, 4, 700)
The element 700 is present at index 4
4

>>> rec_linear_search([0, 30, 500, 100, 700], 0, 4, 30)
The element 5 is present at index 1
1

>>> rec_linear_search([0, 30, 500, 100, 700], 0, 4, -6)
The element -6 is not present in the array
'''
-1
"""
if (0 > high or high >= len(sequence)) or (0 > low or low >= len(sequence)):
raise Exception("Invalid upper or lower bound!")

if high < low:
return -1
try:
if sequence[low] == target:
return low
if sequence[high] == target:
return high
return rec_linear_search(sequence, low + 1, high - 1, target)
except IndexError:
print('Invalid upper or lower bound!')
if sequence[low] == target:
return low
if sequence[high] == target:
return high
return rec_linear_search(sequence, low + 1, high - 1, target)


if __name__ == "__main__":
Expand Down