In Python 2.7, I created an anagram solver that takes an input, discovers all permutations of it, and then checks if it matches any of the words in this dictionary text file. It works fine, however, there is one flaw. It does not only provide precise matches but also matches when the anagram is simply a portion of a word in the text file.
Example:
When comparing permutations with the dictionary, how might I just output precise matches? I attempted the == operator as said in this article by scaler topics in the check function, but that made the program worse.
Example:
This is because several terms, such as hypnotist and hypnotic, contain the word hypnot. With this flaw, it's still possible to solve the anagram, but I want the software to be as simple as possible.Input scrambled word: python
Possible Word: ypnoth
Possible Word: python
Possible Word: hypnot
Code:
# import permutations module
from itertools import permutations as prm
# take input
scrambled_word = list(str(raw_input("Input scrambled word: ")))
# empty lists that will be appended to later
prm_list = []
possible_words = []
# takes each permutation of the input and puts in a list
for i in prm(scrambled_word):
prm_list.append("".join(i))
def check(x, y):
# open list of words
dictionary = file('E:\MRP\Text_Files\dictionary.txt')
# check each line in the dictionary against each item
# in the list of permutations and add it to another empty list if it's a match
for line in dictionary:
for i in x:
if i in line:
y.append(i)
check(prm_list, possible_words)
# delete duplicates
possible_words = list(set(possible_words))
# print out possible words
for i in possible_words:
print "Possible Word: " + i