【问题标题】:Python what is the fastest way to find the most common letter in a list of words? [closed]Python在单词列表中找到最常见字母的最快方法是什么? [关闭]
【发布时间】:2016-05-10 14:16:56
【问题描述】:

我正在尝试为刽子手编写一个 AI,它可以猜测您所想的单词。在猜对一个元音后,我希望它找到最常见的字母来猜下一个字母。我怎样才能做到这一点? 谢谢。

【问题讨论】:

  • 找到一个单词语料库,过滤具有正确长度的单词并将元音放在正确的位置。
  • 如果你写的只是一个刽子手游戏,你可能不应该关心什么是“最快的”。如果响应需要 0.001 秒而不是 0.00001 秒,用户不会注意到。写一些可行的东西,然后当且仅当你发现瓶颈时进行优化。

标签: python list artificial-intelligence counter


【解决方案1】:

如果它必须非常快,我会写一个c extension

仅使用 python,有很多方法可以做到这一点。您可以测试一些,看看哪个是最快的。因为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]

或者:

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

【讨论】:

    猜你喜欢
    • 2021-07-17
    • 2020-01-28
    • 1970-01-01
    • 2018-06-07
    • 1970-01-01
    • 1970-01-01
    • 2020-12-11
    • 1970-01-01
    • 2021-11-24
    相关资源
    最近更新 更多