python-3.xlistalgorithmlinear-search

I can't understand how those functions link together


I was going through an algorithm course and it demonstrates a basic linear search algorithm and it uses a verify function to verify if the index is right or wrong but I don't understand how the verify function connects with the linear_search function.

Take a look at the code:

def linear_search(list, target):
    for i in range(0, len(list)):
        if list[i] == target:
            return i
    return None

def verify(index):
    if index != None:
        print(f'The index is: {index}')
    else:
        print("The Value does not exist")

numbers = [1,2,3,4,5,6,7,8,9,10]
result = linear_search(numbers, 5)
verify(result)

Solution

  • You can do this step by step:

    Lets look at the first function:

        for i in range(0, len(list)):
            if list[i] == target:
                return i
        return None 
    

    The function linear_search is used to search for a target value in the given list by looping through the given list. It checks if each element is equal to the target value, and if the target value is found, it returns the index of the target value in the list, otherwise it returns None. Note that what is being returned by this function is an index of the target value.

    Now let's look at the second function:

    def verify(index):
        if index != None:
            print(f'The index is: {index}')
        else:
            print("The Value does not exist")
    

    The function verify checks if the result of the linear_search function is valid or not. As we noted earlier, linear_search returns the index of the target, so here if the index is not None, it prints the index of the target value. If the index is None, it prints a message saying that the target value does not exist in the list. That is how these two functions are related. In practice, linear_search function is enough and can be modified a bit just to produce the same result without the second function.