Linear Search Python

NacDan picture NacDan · Apr 9, 2017 · Viewed 11.3k times · Source

I am new to python and we were given an assignment to create a linear search program that does not use "in" or index. The program compiles but says that every number I input is not in the list. I also have to do the same thing for a binary search but I'm doing things one at a time ha. Any help is appreciated!

PS: How could I show what index it is in without using the "index" function?

def linearSearch(intList,target):
    found = False
    position = 0
    while position < len(intList) and not found:
        if intList[position] == target:
            found = True
        position = position + 1

    return found

linearList = [3,5,9,7,6,12,15,9,1]
numInput = input("What number are you looking for? ")
numFound = linearSearch(linearList, numInput)
if numFound:
    print("The number is in index: ")
else:
    print("The number is not in the list")

Answer

OneCricketeer picture OneCricketeer · Apr 9, 2017

1) Start position = -1

2) return position

3) You want to position+=1 before if intList[position] == target: and you want to break when you do find the element. You then don't need found

Something is found when linearSearch(linearList, numInput) > 0

Then, your code just doesn't work because the list contains ints whereas input will always return a string. You must use int(input(".."))