Answers for "recursive linear search python"

0

recursive linear search python

"""
This is rather straight forward:
The 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.
"""

def recrsv_lin_search (target, lst, index=0):
    if index >= len(lst):
        return False
    if lst[index] == target:
        return index
    else:
        return recrsv_lin_search(target, lst, index+1)

#test it
example = [1,6,1,8,52,74,12,85,14]
#check if 1 is in the list (should return 0, the index of the first occurrence
print (recrsv_lin_search(1,example))
#check if 8 is in the list (should return 3, the index of the first and only occurrence)
print (recrsv_lin_search(8,example))
#check if 14 is in the list (should return 8, the index of the last occurrence)
print (recrsv_lin_search(14,example))
#check if 53 is in the list (should return False)
print (recrsv_lin_search(53,example))
Posted by: Guest on August-08-2021

Python Answers by Framework

Browse Popular Code Answers by Language