# Better version of anagram solver. # This version prunes the recursion if prefix is impossible from BinarySearch import * def anagrams(lexicon, charsToUse, prefix=''): """ Return a list of anagrams, formed with prefix followed by charsToUse. lexicon a list of words (presumed to be alphabetized) charsToUse a string which represents the characters to be arranged prefix a prefix which is presumed to come before the arrangement of the charsToUse (default empty string) """ global numCalls numCalls += 1 # you can uncomment the following line for convenient debugging info # print ' '*len(prefix) + 'Call with "%s(%s)"' % (prefix, charsToUse) solutions = [] if len(charsToUse) > 1: for i in range(len(charsToUse)): # pick charsToUse[i] next newPrefix = prefix + charsToUse[i] if prefixSearch(lexicon, newPrefix): # worth exploring newCharsToUse = charsToUse[ : i] + charsToUse[i+1 : ] solutions.extend(anagrams(lexicon, newCharsToUse, newPrefix)) else: # check to see if we have a good solution candidate = prefix + charsToUse if search(lexicon, candidate): # use binary search solutions.append(candidate) return solutions if __name__ == '__main__': from FileUtilities import * print 'Will begin by reading the file of words.' words = readWordFile() words.sort() puzzle = raw_input('enter a string of characters to use: ') while puzzle: numCalls = 0 solutions = anagrams(words, puzzle.replace(' ','')) # ignore spaces from input print '(total number of calls was %d)'%numCalls print 'There were %d solutions reported' % len(solutions) verbose = raw_input('Would you like to see them? [y/n] ') if verbose and verbose.strip()[0].lower() == 'y': print '\n'.join(solutions) puzzle = raw_input('enter a string of characters to use: ')