Given an input of scrambled word, and I have a file of English words. I want to find all possible words that can be formed from the scrambled word.
from itertools import permutations
def unscramble(scrambled_word):
length=len(scrambled_word)
unscrambled_word=[]
for r in range(length):
if r >= 2:
permutation_object=permutations(scrambled_word, r)
unscrambled_list=[''.join(permutation) for permutation in permutation_object]
unscrambled_word.extend(unscrambled_list)
return unscrambled_word
def english_words():
with open("english_words.txt") as file_object:
content=file_object.read()
return content
unscrambled_word=unscramble("nidswow")
english_words=english_words()
for word in unscrambled_word:
if word in english_words:
print(word)
As suggested by Tim's comment, one way to solve this would be using a dictionary of the English words and having the sorted words as keys. To populate the dictionary, just iterate over each English word, sort it to get the key, and append the word to the dict value, which can be an empty list to begin with (defaultdict is perfect for this). For this example, I got the English words from here.
The dictionary now looks something like this:
To get the matching words out of a scrambled one, you can use a similar approach. First, you generate a key by sorting the scrambled word, then you use the key to get the list of matching words from the dictionary.
Output: