def makeNeighbors(): # Open the file f = open("words.dat", "r") # Read the words into the "master" wordList masterWordList = [] for line in f: masterWordList.append(line.rstrip()) # From the master wordList, generate 5 word dictionaries, each containing all 4-letter words # obtained by removing the letter in a particular position of all the words. In other words, # shortWordDicts[0] contains all words in masterWordList with the first letter removed, as # dictionary keys, with the removed letters appearing as a list of corresponding values. shortWordDicts = [{}, {}, {}, {}, {}] for i in range(5): for x in masterWordList: shortWord = x[0:i]+x[i+1:5] letter = x[i] if shortWord not in shortWordDicts[i]: shortWordDicts[i][shortWord] = [letter] else: shortWordDicts[i][shortWord].append(letter) # Prepare a dictionary that will eventually keep track of the word-neighbors # Initially all neighborlists are empty wordDict = {} for word in masterWordList: wordDict[word] = [] # Process each word in the master list for word in masterWordList: for i in range(5): shortWord = word[0:i] + word[i+1:5] # Create a 4-letter word for it by removing a letter in the ith position missingLetters = shortWordDicts[i][shortWord] # Look in the appropriate 4-letter word list to find matches wordDict[word].extend([word[0:i] + letter + word[i+1:5] for letter in missingLetters]) wordDict[word].remove(word) # a word should not be in its own set of neighbors return wordDict