我正在为MasterMind编写一个求解器,我必须在其中进行猜测和回答并返回一些黑色和白色钉子的表示,其中黑色栓钉在正确的位置表示正确的颜色,并且白色栓钉代表错误点的正确颜色。我必须运行此代码大约200万次迭代,因此它需要尽可能快。目前最大的时间汇是分裂和索引调用,但我不知道如何删除它们。有关如何在保持其功能的同时更快地运行此代码的任何想法?
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
答案 0 :(得分: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)]