[英]Check which words from a list could be formed with a string of letters
系統: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
您的代碼中的問題是,您正在比較完全匹配,在大多數情況下,即完全不使用字母。 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']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.