Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why linear_search function do not work correctly?

Why this code works only if target==theFirstElement ? it return None even though target==5 or any other element in the list.

def linear_search(lista, target):
    for i in range(8):
        if lista[i]==target:
            return i
        return None

def verify(index):
    if index is not None:
        print("Target found at index:", index)
    else:
        print ("Target not found in list")

numbers =[1,2,3,4,5,6,7,8]

result=linear_search(numbers, 4)

verify(result)

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

There is a bug with your code: you should return None only once the for loop is done and you visited all the elements:

def linear_search(lista, target):
    for i, elem in enumerate(lista):
        if elem == target:
            return i
    # if you don't find the target return None
    return None
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading