I am writing a solver for MasterMind in which I must take in a guess and an answer and return some representation of the number of black and white pegs where a black peg represents a correct color in the correct spot and a white peg represents a correct color in the incorrect spot. I have to run this code for about 2 million iterations and so it needs to be as fast as possible. Currently the biggest time sinks of this are the split and index calls, but I’m not sure how to remove them. Any ideas on how to make this code run faster while maintaining its functionality?
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
To ensure clarity. My input is a string of four colors separated by spaces, and my output doesn’t have to have any particular form so long as it is unique for every combination of black and white pegs.
After some heavy optimization This is the current state of the code:
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
Optimizing further, kinda going back to some original code, this version is actually the fastest of them all. By about a factor of 4 over the first and a factor of 2 over the second.
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
If I’m reading your question correctly, this code should do what you need:
zip()zips together two sequences: