【发布时间】:2016-06-24 09:37:54
【问题描述】:
这个程序接受用户的输入,例如“aeoritre”,并输出可以由这些字母组成的任何单词。 dictionary.txt 文件包含单词表。
我的问题是如何只输出字符串匹配的最长单词而不是打印所有单词?同样,如果单词最长,则只输出其中一个。提前致谢!
from collections import Counter
words = []
def isAnAnagram(word, user):
word_counter = Counter(word)
input_counter = Counter(user)
return all(count <= input_counter[key] for key, count in word_counter.items())
def getAnagrams(user):
lister = [word for word in words if len(word) <= len(user) ]
for item in lister:
if isAnAnagram(item, user):
yield item
with open('Dictionary.txt', 'r') as f:
allwords = f.readlines()
f.close()
for x in allwords:
x = x.rstrip()
words.append(x)
inp = 1
while inp != "99":
inp = input("enter word:")
result = getAnagrams(inp)
print(list(result))
print(len(list(result)))
【问题讨论】: