系统:Mac Python 2.7
您好, 所以我有一个列表,其中包含我在网上找到的英语词典中的单词。接下来,我有一个字符串 小写字母。我想要做的是找到列表中的所有单词(英语词典),这些单词由字符串中的字母组成,并将它们保存到单独的列表中。此外,我不希望能够重复使用字母(胶水 - >欢乐合唱团),但可以重新排列给出的字母。示例字符串可以是“hideg”,结果应生成包含以下内容的列表:
['hide','hid','hie','dig','eh','he','hi','die','ed','id','i']
这是我到目前为止所得到的(注意:myWord是列表(英文字典),myLetters是字符串):
def validWord(myWord, myLetters):
myLetters = "".join(sorted(myLetters))
matches = []
for i in myWord:
if "".join(sorted(i)) in myLetters:
matches.append(i)
return matches
答案 0 :(得分:0)
您的代码中的问题是您要比较完全匹配,在大多数情况下,字母未完全使用,即。 hide!= hideg,但当然它可以形成这个词。
一种简单的方法(尽管未经过优化)是使用collections.Counter,如下所示:
In [32]: from collections import Counter
In [33]: words = ['hide','hid','hie','dig','eh','he','hi','die','ed','id','i']
In [34]: letters = 'hide'
In [35]: def valid_word(words, letters):
....: results = []
# looping through words list and do a comparison
....: for word in words:
# build a letter counter for letters
....: letter_counter = Counter(letters)
# subtract their letter count, -ve means cannot form the word
....: letter_counter.subtract(Counter(word))
....: if any(c < 0 for c in letter_counter.values()):
....: continue
# only append the result if >=0 letters left in counter
....: results.append(word)
....: return results
....:
用法:
In [36]: valid_word(words, letters)
Out[36]: ['hide', 'hid', 'hie', 'eh', 'he', 'hi', 'die', 'ed', 'id', 'i']
In [37]: valid_word(words, 'hideg')
Out[37]: ['hide', 'hid', 'hie', 'dig', 'eh', 'he', 'hi', 'die', 'ed', 'id', 'i']