# # linear search for user-supplied word # words in list can be in any order # commands: s word -- search for word # a word -- add word to list # p -- print the list # # Matt Bishop, MHI 289I, Fall 2019 # # 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): # 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 that you found nothing return -1 # append words to a list # parameters: none # returns: nothing def addword(word, wordlist): # use existing routine to see if this is a duplicate found = search(word, wordlist) if (found == -1): # nope -- add it wordlist.append(word) print("Added word '%s' to list" % word) else: # yep -- say so 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; need a dummy non-empty string to go in 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) # # and away we go! # main()