Contents

  1. search.py

search.py

# Demonstrate implementation of the linear search technique.
# Two implementations: one returns either True or False; 
# the other returns the position where the element was found
# Sara Sprenkle

NOT_FOUND = -1

def main():
    
    integers = range(1, 20, 2)
    print("The list we are searching: ", integers)
    print()
    
    findMeList = [1, 4, 15, 16, 17]
    
    for key in findMeList:
        print("Search for", key)
        found = linearSearch(integers, key)
        print("Linear: Found?", found)
        if found:
            print("Pos: ", linearSearchReturnPos(integers, key))
        # You probably wouldn't really use both implementations
        # of linear search.  Just for demonstration
        print()


def linearSearch(searchlist, key):
    """Returns True iff the key is in searchlist."""
    for elem in searchlist:
        if elem == key:
            return True
    return False

def linearSearchReturnPos(searchlist, key):
    """Returns the position of the key in searchlist, if found;
    -1 if not found."""
    for pos in range(len(searchlist)):
        if searchlist[pos] == key:
            return pos
    return NOT_FOUND
    
main()

Generated by GNU Enscript 1.6.6.