@@ -30,47 +30,48 @@ def linear_search(sequence: list, target: int) -> int:
30
30
1
31
31
32
32
>>> linear_search([0, 5, 7, 10, 15], 6)
33
-
33
+ -1
34
34
"""
35
35
for index , item in enumerate (sequence ):
36
36
if item == target :
37
37
return index
38
- return None
38
+ return - 1
39
39
40
40
41
41
def rec_linear_search (sequence : list , low : int , high : int , target : int ) -> int :
42
- '''
42
+ """
43
43
Pure implementation of recursive linear search algorithm in Python
44
44
45
- :param sequence: An array of items
45
+ :param sequence: a collection with comparable items (as sorted items not required
46
+ in Linear Search)
46
47
:param low: Lower bound of the array
47
48
:param high: Higher bound of the array
48
49
: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
50
51
51
52
Examples:
52
53
>>> rec_linear_search([0, 30, 500, 100, 700], 0, 4, 0)
53
- The element 0 is present at index 0
54
-
54
+ 0
55
+
55
56
>>> rec_linear_search([0, 30, 500, 100, 700], 0, 4, 700)
56
- The element 700 is present at index 4
57
-
57
+ 4
58
+
58
59
>>> rec_linear_search([0, 30, 500, 100, 700], 0, 4, 30)
59
- The element 5 is present at index 1
60
-
60
+ 1
61
+
61
62
>>> 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
+
64
68
if high < low :
65
69
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 )
74
75
75
76
76
77
if __name__ == "__main__" :
0 commit comments