Search code examples
pythonlinear-search

Code for linear search in python not working and outputs wrong text


I need to write a program that does linear search on a character within a sentence. I have to do it without using any inbuilt functions except for print().

The program should output what index the character is at.

If the character isn't in the sentence it should output -1 as the index.

My code outputs the following:

Enter a sentence: Hello
Enter a character: e
The character is -1.
The character is 1 on the index.

Even though it should only output:

Enter a sentence: Hello
Enter a character: e   
The character is 1 on the index.

Below is my code:

def linear_search(intList,target):
    found = False
    count = 0
    while count < len(intList):
        if intList[count] == target:
            print("The character is", count, "on the index.")
            found = True
            break
        if intList[count] != target:
            print("The character is -1.")
            count = count + 1

    return count

sentence = input('Enter a sentence: ')
character = input('Enter a character: ')
character_found = linear_search(sentence,character)

Many thanks for your help!


Solution

  • Your problem is that you output the undesired result before checking the entire string. You can solve this problem pretty easily by simply checking if the character was found after the conclusion of the while loop.

    def linear_search(intList,target):
            found = False
            count = 0
            while count < len(intList):
                if intList[count] == target:
                    print("The character is", count, "on the index.")
                    found = True
                    break
                else: count += 1
            if not found:
                print("The character is -1.")
    
        return count
    
    sentence = input('Enter a sentence: ')
    character = input('Enter a character: ')
    character_found = linear_search(sentence,character)