I'm building a text-based Wordle clone in Python. Each guessed letter is displayed with different brackets: parentheses mean the letter is not in the answer, curly braces mean it is in the answer but in the wrong position, and square brackets mean it is in the correct position. The problem appears when the guess contains a letter more times than the answer does. For example, with the answer `wally` and the guess `lalal`, the program labels letters incorrectly because it checks and modifies `answer` while processing the guess from left to right. How can I correctly handle duplicate letters so that each occurrence in the answer is used at most once?
3 Answers
Use two passes instead of deciding everything in one loop. First mark letters that are exactly correct and remove those positions from consideration. Then check the remaining guessed letters against the remaining answer letters for misplaced matches. Keep the original answer unchanged while comparing positions; mutating it during the loop causes later indexes and membership checks to refer to the wrong string. Each answer letter should be consumed at most once, so extra copies in the guess become incorrect.
For a five-letter game, you can also count how many of each letter remain after exact matches. Subtract exact matches first, then process the non-exact guesses: if the remaining count for that letter is positive, it is a wrong-position match and the count decreases; otherwise it is incorrect. This handles cases like repeated letters without relying on string replacement.
A simple way is to store a result for every guess position and track which answer positions have already been used. First loop through the guess and mark exact matches as `[x]`. In a second loop, skip those positions and search for an unused matching letter elsewhere; mark it as `{x}` and mark that answer position used. If no unused match exists, mark it as `(x)`. Do not replace letters with `*` in the answer string, because that makes the original word harder to reason about and can alter later comparisons.
The important detail is that an incorrect guess should not consume an answer letter. Only exact or misplaced matches should mark a letter as used.

That explains why the later letters were getting the wrong bracket. I was changing the answer while still using it for the position checks.