def anagrams_1(phrase): """Strategy: see anagrams_1_recursive""" found = set() phrase = ''.join(phrase.split()) match_words = match_words_for(phrase) match_tree = match_tree_from(match_words) for x in anagrams_1_recursive('', phrase, match_tree, match_tree, []): x = ' '.join(sorted(x)) if x not in found: found.add(x) yield x
def anagrams_2(phrase): """Strategy: Naively put: generate all combinations of match words and filter out those that don't match. Actually: recursively build combinations of match words, aborting when reaching dead ends. """ phrase = ''.join(phrase.split()) phrase_counter = Counter(phrase) match_words = match_words_for(phrase) # Find the big-word results first match_words = sorted(match_words, key=lambda w: -len(w)) candidate_words = [ (word, Counter(word)) for word in match_words ] for x in anagrams_2_recursive(phrase_counter, candidate_words): yield x