2016-05-10 8 views
-1

私はあなたが考えている言葉を推測するハングマンのAIを書こうとしています。母音を正確に推測した後、次の文字の推測のために最も一般的な手紙を見つけたいと思う。これどうやってするの?おかげさまで Pythonどのような単語のリストで最も一般的な文字を見つけるための最速の方法は何ですか?

+0

[collections.Counter](https://docs.python.org/2/library/collections.html#collections.Counter) –

+1

持つ単語をフィルタリングし、ワードコーパスを探します正しい長さで正しい母音にその母音を持つエース。 – Selcuk

+5

あなたが書いているのが絞首刑執行人のゲームであれば、「最速」なんて心配しないでください。ユーザーは、0.00001秒の代わりに応答するのに0.001秒かかる場合は気付かないでしょう。うまくいくものを書いて、ボトルネックを特定した場合にのみ、後で最適化してください。 – Kevin

答えて

1

本当に速くなければならない場合は、cextensionと書いてください。

pythonだけを使用すると、それを行う方法はたくさんあります。あなたはいくつかをテストし、どれが最速かを見ることができます。

def commonLetter(words): 
    joined = ''.join(words) # creating one string from all the words 
    letterDict = {} # will contain the number of occurences for each letter 
    def addToDict(letter): 
     try: letterDict[letter] += 1 
     except: letterDict[letter] = 1 
    map(addToDict, joined) # applying addToDict to all the letters 
    return max(letterDict.keys(), key=lambda letter: letterDict[letter]) 

words = [ 
    'Python', 'what', 'is', 'the', 
    'fastest', 'way', 'to', 'find', 
    'the', 'most', 'common', 'letter', 
    'in', 'a', 'list', 'of', 'words' 
] 
print commonLetter(words) # outputs 't' 

ます。また、試すことができます:

def commonLetter(words): 
    joined = ''.join(words) # creating one string from all the words 
    tuples = map(lambda letter: (letter, joined.count(letter)), set(joined)) 
    return max(tuples, key=lambda tup: tup[1])[0] 
をPythonの組み込み関数が最適化されているので、私はそれは私がそれを行うだろう方法ですので、彼らに私ができるの代わりに、ループの限りを使用して試してみました

または:

def commonLetter(words): 
    joined = ''.join(words) # creating one string from all the words 
    return Counter(joined).most_common(1)[0][0] 
関連する問題