# reads in a list of words, linear search for user-supplied word # words in list can be in any order # # Matt Bishop, MHI 289I, Fall 2023 # this is global just to emphasize how that works wordlist = [] # search a list of words for a word (linear search) # parameters: word, the word to find in the list # returns: index (+1) of word in list # -1 if not in list # globals: wordlist, list to search def search(word): # declaration global wordlist # go through the list a word at a time for i in range(len(wordlist)): # see if there is a match if wordlist[i] == word: # yep! return position (success) return i + 1 # return what you found return -1 # load words from a file to a list; assumes one word per line # note: lines separated by *newlines*, not *carriage returns* # parameters: none # returns: True if words loaded successfully # False if problem opening file # globals: wordlist, list to append words to def loadfile(): # declaration global wordlist # open the file, trapping errors try: infile = open("listu.txt", "r") except IOError as errmsg: # say why it failed, return error code print("Could not open 'listu.txt':", errmsg) return False # go through the file line by line for i in infile: # strip any leading and trailing white space (inc. newline) i = i.strip() # tack the word onto the list wordlist.append(i) # all done! close file and return success code infile.close() return True # this puts it all together def main(): # declaration global wordlist # load the word list; on error, quit if not loadfile(): return # loop while True: # read in word; quit on EOF try: find = input("What word should I look for EOF to quit)? ") except EOFError: return # find the word if it's there found = search(find) # announce result if found == -1: print("'%s' is not in the list" % find) else: print("'%s' is word number %d" % (find, found)) main()