MCPcopy Create free account
hub / github.com/bslatkin/effectivepython / find_anagrams

Function find_anagrams

example_code/item_118.py:94–112  ·  view source on GitHub ↗

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)

Source from the content-addressed store, hash-verified

92import itertools
93
94def 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
115assert find_anagrams("pancakes", ["scanpeak"]) == ["scanpeak"]

Callers 1

item_118.pyFile · 0.70

Calls

no outgoing calls

Tested by

no test coverage detected