recursive linear search python

Solutions on MaxInterview for recursive linear search python by the best coders in the world

showing results for - "recursive linear search python"
Sophia
14 Jun 2017
1"""
2This is rather straight forward:
3The function just needs to look at a supplied element, and, if that element isn't the one we're looking for, call itself for the next element.
4"""
5
6def recrsv_lin_search (target, lst, index=0):
7    if index >= len(lst):
8        return False
9    if lst[index] == target:
10        return index
11    else:
12        return recrsv_lin_search(target, lst, index+1)
13
14#test it
15example = [1,6,1,8,52,74,12,85,14]
16#check if 1 is in the list (should return 0, the index of the first occurrence
17print (recrsv_lin_search(1,example))
18#check if 8 is in the list (should return 3, the index of the first and only occurrence)
19print (recrsv_lin_search(8,example))
20#check if 14 is in the list (should return 8, the index of the last occurrence)
21print (recrsv_lin_search(14,example))
22#check if 53 is in the list (should return False)
23print (recrsv_lin_search(53,example))