Skip to content

Commit dbf677f

Browse files
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
1 parent 7b37eb8 commit dbf677f

File tree

1 file changed

+22
-21
lines changed

1 file changed

+22
-21
lines changed

searches/linear_search.py

Lines changed: 22 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -30,47 +30,48 @@ def linear_search(sequence: list, target: int) -> int:
3030
1
3131
3232
>>> linear_search([0, 5, 7, 10, 15], 6)
33-
33+
-1
3434
"""
3535
for index, item in enumerate(sequence):
3636
if item == target:
3737
return index
38-
return None
38+
return -1
3939

4040

4141
def rec_linear_search(sequence: list, low: int, high: int, target: int) -> int:
42-
'''
42+
"""
4343
Pure implementation of recursive linear search algorithm in Python
4444
45-
:param sequence: An array of items
45+
:param sequence: a collection with comparable items (as sorted items not required
46+
in Linear Search)
4647
:param low: Lower bound of the array
4748
:param high: Higher bound of the array
4849
:param target: The element to be found
49-
:return: Index of the key or -1 if key not found or None in case of an exception
50+
:return: Index of the key or -1 if key not found
5051
5152
Examples:
5253
>>> rec_linear_search([0, 30, 500, 100, 700], 0, 4, 0)
53-
The element 0 is present at index 0
54-
54+
0
55+
5556
>>> rec_linear_search([0, 30, 500, 100, 700], 0, 4, 700)
56-
The element 700 is present at index 4
57-
57+
4
58+
5859
>>> rec_linear_search([0, 30, 500, 100, 700], 0, 4, 30)
59-
The element 5 is present at index 1
60-
60+
1
61+
6162
>>> rec_linear_search([0, 30, 500, 100, 700], 0, 4, -6)
62-
The element -6 is not present in the array
63-
'''
63+
-1
64+
"""
65+
if (0 > high or high >= len(sequence)) or (0 > low or low >= len(sequence)):
66+
raise Exception("Invalid upper or lower bound!")
67+
6468
if high < low:
6569
return -1
66-
try:
67-
if sequence[low] == target:
68-
return low
69-
if sequence[high] == target:
70-
return high
71-
return rec_linear_search(sequence, low + 1, high - 1, target)
72-
except IndexError:
73-
print('Invalid upper or lower bound!')
70+
if sequence[low] == target:
71+
return low
72+
if sequence[high] == target:
73+
return high
74+
return rec_linear_search(sequence, low + 1, high - 1, target)
7475

7576

7677
if __name__ == "__main__":

0 commit comments

Comments
 (0)