In: Computer Science
PYTHON:
Write a recursive function named linear_search that searches a list to find a given element. If the element is in the list, the function returns the index of the first instance of the element, otherwise it returns -1000.
Sample Output
>> linear_search(72, [10, 32, 83, 2, 72, 100, 32])
4
>> linear_search(32, [10, 32, 83, 2, 72, 100, 32])
1
>> linear_search(0, [10, 32, 83, 2, 72, 100, 32])
-1000
>> linear_search('a', ['c', 'a', 'l', 'i', 'f', 'o', 'r', 'n', 'i', 'a'])
1
Use this template:
=============================================================================
def linear_search(ele, array):
"""searches the given list for the given element
INPUT:
* ele - the element
* array - the list
OUTPUT: the index of the first instance of the element in the list,
or -1000 if it is not in the list.
"""
pass
def linear_search(ele, array):
for i in range(len(array)):
if array[i] == ele:
return i
return -1000
print(linear_search(72, [10, 32, 83, 2, 72, 100, 32]))
print(linear_search(32, [10, 32, 83, 2, 72, 100, 32]))
print(linear_search(0, [10, 32, 83, 2, 72, 100, 32]))
print(linear_search('a', ['c', 'a', 'l', 'i', 'f', 'o', 'r', 'n', 'i', 'a']))
4
1
-1000
1