def anagram(word,check):
for letter in word:
if letter in check:
check = check.replace(letter, '')
else:
return 0
return 1
while True:
f = open('dictionary.txt', 'r')
try:
user_input = input('Word? ')
for word in f:
word = word.strip()
if len(word)==len(user_input):
if word == user_input:
continue
elif anagram(word, input):
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 EOFError:
break
f.close()
该函数按我希望的方式工作,但我需要一些输出帮助。我希望输出结果在一行中,措辞应该反映找到的字符的数量。 (即'只有一个字谜','anagrams','没有anagrams',或'这个词不在字典中')代码中的注释是我尝试过的。谢谢你的帮助。Python 3.3:Anagram函数的输出
您应该在'anagram()'中返回'True'和'False'。 –
这不会解决您的问题,但我建议将'if len(word)== len(user_input)'和'if word == user_input'行移入'anagram'函数。 “是否”字“和”检查“长度相同?”和“是”字和“检查”相同的单词?“在检查字谜时,问的是合乎逻辑的问题。 – Kevin
另外,我认为你有一个bug,因为'anagram(“aab”,“baa”)'返回0. – Kevin