0

我正在为 MasterMind 编写一个求解器,其中我必须接受猜测和答案,并返回一些表示黑色和白色钉子数量的表示,其中黑色钉子代表正确位置的正确颜色,白色钉子代表正确颜色在不正确的位置。我必须运行这段代码大约 200 万次迭代,因此它需要尽可能快。目前最大的时间消耗是 split 和 index 调用,但我不知道如何删除它们。关于如何在保持其功能的同时使此代码运行得更快的任何想法?

def returnPegs(guess, answer):
        guessList = guess.split(" ")
        answerList = answer.split(" ")
        response = ""
        iterator = [0,1,2,3]
        for i in iterator:
            if answerList[i] == guessList[i]:
                response = response + "B"
                guessList[i] = "alsoNotAColor"
                answerList[i] = "notAColor"
        for j in iterator:
            if guessList[j] in answerList:
                response = response + "W"
                answerList[answerList.index(guessList[j])] = "notAColor"
                guessList[j] = "alsoNotAColor"
        return response

以确保清晰度。我的输入是由空格分隔的四种颜色的字符串,我的输出不必具有任何特定的形式,只要它对于黑白钉的每种组合都是唯一的。

经过一些重度优化后这是代码的当前状态:

 def returnPegs(guess, answer):
    pegs = 0 
    for answerPeg, guessPeg in zip(answer, guess):
        if answerPeg == guessPeg:
            pegs += 5
        elif guessPeg in answer:
            pegs +=1
    return pegs

进一步优化,有点回到一些原始代码,这个版本实际上是所有版本中最快的。大约是第一个的 4 倍,第二个的 2 倍。

def returnPegs(guess, answer):
    response = 0
    iterator = [0,1,2,3]
    for i in iterator:
        if guess[i] == answer[i]:
            response += 5
            guess[i] = "alsoNotAColor"
            answer[i] = "notAColor"
        elif guess[i] in answer:
            response += 1
            answer[answer.index(guess[i])] = "notAColor"
            guess[i] = "alsoNotAColor"
    return response
4

1 回答 1

1

如果我正确阅读了您的问题,则此代码应该可以满足您的需要:

def returnPegs(guess, answer):
    guesses = guess.split()
    answers = answer.split()

    pegs = []

    for answer, guess in zip(answers, guesses):
        if answer == guess:
            pegs.append('B')
        elif guess in answers:
            pegs.append('W')

    return ''.join(pegs)

zip()将两个序列压缩在一起:

>>> a = [1, 2, 3, 4]
>>> b = [5, 6, 7, 8]
>>> zip(a, b)
[(1, 5), (2, 6), (3, 7), (4, 8)]
于 2012-12-05T04:13:47.457 回答