I’m trying to make a program in Python that finds anagrams. Here is my current code:
def anagram(word,checkword):
for letter in word:
if letter in checkword:
checkword = checkword.replace(letter, '')
else:
return False
return True
while True:
f = open('listofwords.txt', 'r')
try:
inputted_word = input('Word? ')
for word in f:
word = word.strip()
if len(word)==len(inputted_word):
if word == inputted_word:
continue
elif anagram(word, inputted_word):
print(word)
#try:
#if word == 1:
#print ('The only anagram for', user_input, 'is', word)
#elif word > 1:
#print ('The anagrams for', user_input, 'are', word)
#except TypeError:
#pass
except:
break
I’m having trouble outputting the anagrams. The anagrams should be in one line, and the wording should reflect the amount of anagrams found. Such as…
"There is only one (insert anagram) for (insert word inputted)"
"There are (insert anagrams) for (insert word inputted)"
"There are no anagrams for (insert word inputted)"
"The (insert word inputted) is not in the dictionary")
Here are a few hints:
First, if you have to print the count of anagrams before you print any of them, you need to hold onto a list of them while you’re looping. Something like this:
Now you just have to figure out how to print the right text at the end, based on what’s in the
anagramslist.As for what you tried:
This can’t possibly work. First,
wordis a word, so it can’t possibly be equal to1, or greater than1. Also, if you’ve only gone through, say, the first 20 words in the dictionary, and found the first anagram, how could you know that this is the only anagram? There may be 1000 of them in the rest of the dictionary. You can’t decide which sentence to print until you’ve finished the whole dictionary.Meanwhile, notice that you have different cases for “There is only one” vs. “not in the dictionary”. So, you need some kind of flag for “found inputted_word in the dictionary”, which you set inside that
ifstatement. Or maybe, you could just leave the special case out—for example, at the end, if you have 0 results, you know it was not in the dictionary. It depends on whether you want more logic at the end, or inside the loop.