2012-12-05 72 views
0

我正在爲MasterMind編寫一個求解器,其中我必須在猜測和答案中返回一些黑色和白色掛釘的表示,其中黑色掛釘代表正確的顏色正確的斑點和白色的栓釘在不正確的斑點中代表正確的顏色。我必須運行這個代碼大約200萬次迭代,所以它需要儘可能快。目前最大的時間點是分割和索引調用,但我不知道如何刪除它們。關於如何使代碼在保持其功能的同時運行得更快的想法?在python中優化MasterMind代碼和字符串操作

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 

回答

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)] 
+0

我真的很喜歡這個答案,但它實際上在我的機器上運行速度稍慢。一旦我擺脫了加入,跑得更快一些,但分離仍然是最大的時間。正則表達式會更快嗎? –

+0

爲什麼你首先使用字符串?在傳入它們之前,先分開'guess'和'answer'。 – Blender

+0

不幸的是,它調用了一個不是我的函數,但如果這是唯一的方法,我可能會重寫它。 –