此函數的目的是比較代碼中出現的顏色次數以及出現在猜測中的次數,以最終確定正確猜測了多少顏色。我現在的代碼遇到了一些錯誤,我相信線的數量可以大大簡化。更具體地說,我認爲我過於複雜了。計算兩個字符串中字符數的問題
有沒有人有更好的方法來解決這個問題的建議?我對編程非常陌生,不勝感激。
validColors = ("R", "G", "B", "Y", "O", "P")
secretCode = "YBGG"
guess = "BYYG"
def correctColorCount(secretCode, guess, validColors):
count = 0
numRedGuess = guess.count("R")
numRedCode = secretCode.count("R")
sumR = numRedGuess + numRedCode
numGreenGuess = guess.count("G")
numGreenCode = secretCode.count("G")
sumG = numGreenGuess + numGreenCode
numBlueGuess = guess.count("B")
numBlueCode = secretCode.count("B")
sumB = numBlueGuess + numBlueCode
numYellowGuess = guess.count("Y")
numYellowCode = secretCode.count("Y")
sumY = numYellowGuess + numBlueCode
numOrangeGuess = guess.count("O")
numOrangeCode = secretCode.count("O")
sumO = numOrangeGuess + numOrangeCode
numPurpleGuess = guess.count("P")
numPurpleCode = secretCode.count("P")
sumP = numPurpleGuess + numPurpleCode
if numRedCode == numRedGuess and sumR != 0 and sumR != 1:
count += 1
if numRedGuess == 2:
count += 1
elif numRedGuess == 3:
count += 2
elif numRedGuess == 4:
count += 3
elif numRedGuess >= 1 and numRedCode >= 1 and sumR != 0 and sumR != 1:
count += 1
if numGreenCode == numGreenGuess and sumG != 0 and sumG != 1:
count += 1
if numGreenGuess == 2:
count += 1
elif numGreenGuess == 3:
count += 2
elif numGreenGuess == 4:
count += 3
elif numGreenGuess >= 1 and numGreenCode >= 1 and sumG != 0 and sumG != 1:
count += 1
if numBlueCode == numBlueGuess and sumB != 0 and sumB != 1:
count += 1
if numBlueGuess == 2:
count += 1
elif numBlueGuess == 3:
count += 2
elif numBlueGuess == 4:
count += 3
elif numBlueGuess >= 1 and numBlueCode >= 1 and sumB != 0 and sumB != 1:
count += 1
if numYellowCode == numYellowGuess and sumY != 0 and sumY != 1:
count += 1
if numYellowGuess == 2:
count += 1
elif numYellowGuess == 3:
count += 2
elif numYellowGuess == 4:
count += 3
elif numYellowGuess >= 1 and numYellowCode >= 1 and sumY != 0 and sumY != 1:
count += 1
if numOrangeCode == numOrangeGuess and sumO != 0 and sumO != 1:
count += 1
if numOrangeGuess == 2:
count += 1
elif numOrangeGuess == 3:
count += 2
elif numOrangeGuess == 4:
count += 3
elif numOrangeGuess >= 1 and numOrangeCode >= 1 and sumO != 0 and sumO != 1:
count += 1
if numPurpleCode == numPurpleGuess and sumP != 0 and sumP != 1:
count += 1
if numPurpleGuess == 2:
count += 1
elif numPurpleGuess == 3:
count += 2
elif numPurpleGuess == 4:
count += 3
elif numPurpleGuess >= 1 and numPurpleCode >= 1 and sumP != 0 and sumP != 1:
count += 1
return count
這是對[策劃](https://en.wikipedia.org/wiki/Mastermind_(board_game))? – TigerhawkT3
這是!如果我包括我的其他程序,會有幫助嗎? –
因爲Mastermind是關於計數元素的,所以試一下['collections.Counter'](https://docs.python.org/3/library/collections.html#collections.Counter),我在[This Let's Code Python: Mastermind視頻](https://www.youtube.com/watch?v=Hv47MO1vQAo)(25行)。 – TigerhawkT3