linear-search

Linear search algorithm partially correct


def linsearch(list, target):
    for i in range(0, len(list)):
            if (list[i] == target):
                return (i)
            else:
                return ("not in list")

list1 = [1,2,3,4,5]

print(linsearch(list1,1))

This is the python program. Whenever I put target as 1 it returns correct index that is 0, but for all other cases it gives the else case prompt i.e. "not in list"


Solution

  • You sohuld not return inside the else statement. If you have a return in both the if and the else, you will never proceed to the second iteration of your for loop.

    You can instead just ommit the else completely and just do nothing when list[i] does not match your target. And only when your code reaches the ent of the for loop without returning on a match, return the "not in list" value.

    def linsearch(list, target):
        for i in range(0, len(list)):
            if (list[i] == target):
                return (i)
        return ("not in list")