Find all anagrams for a word. This function only runs as fast as the test for membership in the 'dictionary' container. Args: word: String of the target word. dictionary: collections.abc.Container with all strings that are known to be actual words. Retu
(word, dictionary)
| 92 | import itertools |
| 93 | |
| 94 | def find_anagrams(word, dictionary): |
| 95 | """Find all anagrams for a word. |
| 96 | |
| 97 | This function only runs as fast as the test for |
| 98 | membership in the 'dictionary' container. |
| 99 | |
| 100 | Args: |
| 101 | word: String of the target word. |
| 102 | dictionary: collections.abc.Container with all |
| 103 | strings that are known to be actual words. |
| 104 | |
| 105 | Returns: |
| 106 | List of anagrams that were found. Empty if |
| 107 | none were found. |
| 108 | """ |
| 109 | permutations = itertools.permutations(word, len(word)) |
| 110 | possible = ("".join(x) for x in permutations) |
| 111 | found = {word for word in possible if word in dictionary} |
| 112 | return list(found) |
| 113 | |
| 114 | |
| 115 | assert find_anagrams("pancakes", ["scanpeak"]) == ["scanpeak"] |