I want to code a function in Python returning all possible anagrams of a word given. Only words of the English language are considered as such.
However, up to now, I only managed to generate all permutations of a word.
import itertools
def anagrams(word):
letters = list(word)
perms = itertools.permutations(letters)
return [''.join(p) for p in perms]
How can I efficiently check and filter for valid English words now?
First you need an English dictionary in Python. I usually use nltk even though there might be better packages. You can install the dictionary of the package by
and then a slight adjustment of your code yields what you want:
For example,
Edit thanks to Kelly Bundy: A far better runtime can be achieved by a different algorithm, that is checking for every correct word if it is an anagram of the input.