# linear search for user-supplied word # words in list can be in any order # ECS 10, Winter 2012 # Matt Bishop import string # this is global just to emphasize how that works wordlist = [ "when", "in", "the", "course", "of", "human", "events" ] # 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 def search(word, wordlist): # base case: list is empty if wordlist == []: return -1 # see if it's the current element # if it is, return position + 1 (the + 1 for humand) if word == wordlist[0]: return 1 # nope; check rest of list k = search(word, wordlist[1:]) # got it! Index is 1 more than previous if k != -1: return k + 1 # return that you found nothing return -1 # append words to a list # parameters: none # returns: nothing def addword(word, wordlist): found = search(word, wordlist) if (found == -1): wordlist.append(word) print("Added word '%s' to list" % word) else: print("'%s' is already in the list (word %d)" % (word, found)) # this puts it all together def main(): # declaration -- using the initial one global wordlist # loop instr = 'next' while len(instr) > 0: # read in word; quit on EOF try: find = input("what do I do (s word, a word, p)? ") except EOFError: return # nothing typed? if len(find) == 0: return # find the word if it's there l = find.split() # # now process the word and command # # first, be sure it's of the right form if len(l) == 0: pass elif len(l) > 2: print("Your input can have only 2 words!") # s word -- find word in the list elif l[0] == 's': # be sure it is of the right form if len(l) == 1: print("s: what should I search for?") else: # look for the word in the list found = search(l[1], wordlist) # announce result if found == -1: print("'%s' is not in the list" % l[1]) else: print("'%s' is word number %d" % (l[1], found)) # a word -- append word to list elif l[0] == 'a': # be sure it is of the right form if len(l) == 1: print("a: what should I add?") else: addword(l[1], wordlist) # p -- print list elif l[0] == 'p': for i in range(len(wordlist)): print("%2d. %s" % (i+1, wordlist[i])) # you got me -- unknown command, so say so else: print("Unknown command '%s'", find) main()