by danbruc · 3y ago · 0 comments
if guess[i] == secret_code[i]:
red += 1
else:
if guess[i] in secret_code:
white += 1
With the secret XXXY a guess of YYYY will be scored as one red and three white but it should be just one red. You have to keep track of which positions in the secret have already been consumed, in this case the Y in the secret gets consumed by the Y in the same position in the guess yielding the one red, for the guess YYYX the Y in the secret will be consumed by the first Y in the guess yielding only one white instead of three. Plus of course a second white for the X. When implementing this, one has to be careful that a white does not consume a later red if one wants to do it in a single loop, i.e. it is not good enough to look for any unconsumed match, it must be unconsumed and also not yield a red. from collections import Counter
def score_guess(guess, secret_code):
red = sum(guess[i] == secret_code[i] for i in range(len(guess)))
total = (Counter(guess) & Counter(secret_code)).total()
return (red, total - red)
assert score_guess('YYYY', 'XXXY') == (1, 0)
assert score_guess('YYYX', 'XXXY') == (0, 2)
(The `&` on `Counter` computes minimum of the two counts.)