# reads in a list of words, binary search for user-supplied word # assumes sorted list # Matt Bishop, Mar. 7, 2012 # for ECS 10 Winter 2012 import string # search a list of words for a word (binary search) # parameters: word, the word to find in the list # wordlist, the list of words # low, low bound of search in wordlist # high, high bound of search in wordlist # returns: index (+1) of word in list # -1 if not in list def search(word, wordlist, low, high): # if low ever passes high, the word isn't in the list if low > high: return -1 # check the middle word mid = (low + high) // 2 if word == wordlist[mid]: # match -- we're done! return mid + 1 elif word < wordlist[mid]: # word comes before middle word # reduce the high index of the interval return search(word, wordlist, low, mid-1) else: # word comes after middle word # advance the low index of the interval return search(word, wordlist, mid+1, high) # append words from a file to a list; assumes one word per line # note: lines separated by *newlines*, not *carriage returns* # parameters: wordlist, list to append words to # returns: True if words loaded successfully # False if problem opening file def loadfile(wordlist): # open the file, trapping errors try: infile = open("list.txt", "r") except IOError as errmsg: # say why it failed, return error code print("Could not open 'list.txt':", errmsg) return False # go through the file line by line for i in infile: # strip any 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(): # initialize word list wordlist = [] # load the word list; on error, quit if not loadfile(wordlist): 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, wordlist, 0, len(wordlist)-1) # announce result if found == -1: print("'%s' is not in the list" % find) else: print("'%s' is word number %d" % (find, found)) main()