How should I handle duplicate letters when scoring a Wordle-style guess in Python?

0
0
Asked By MellowPine42 On

I'm building a text-based Wordle clone in Python. I display each guessed letter 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. My current code checks each character and replaces matched letters in the answer with '*'. However, duplicate letters are handled incorrectly. For example, with the answer `wally` and the guess `lalal`, the program marks letters incorrectly because it appears to reuse or alter the same occurrence more than once. How can I score the guess correctly so that each letter in the answer is used only once, prioritizing letters in the correct position before checking for misplaced letters?

2 Answers

Answered By QuietMaple18 On

The important rule is that a matching letter must be marked as unavailable after it is used. For example, if the answer is `worst` and the guess contains two `r` characters, only one of them can receive a match because the answer contains only one `r`. The same applies to repeated letters in `wally`: exact matches should be claimed first, then only the remaining copies can receive the wrong-position label. Replacing characters with `*` can work as a temporary pool, but it is safer and clearer to use a separate list or dictionary of letter counts instead of mutating the answer itself.

Answered By OrbitCedar7 On

Use two passes. First mark every exact match and remove those letters from the pool of available answer letters. Then process the remaining guess letters for misplaced matches. This prevents duplicate guesses from claiming the same answer letter more than once. Also avoid changing `answer` while using `answer[index]` for comparisons, because replacing characters changes the indexes you are checking. A simple approach is to keep a result list and a count of unmatched letters, for example: `result = [None] * len(answer)` and `remaining = {}`. First loop through both strings and mark exact matches as `[` + letter + `]`, while counting only the answer letters that were not matched. In the second loop, skip exact matches; if the guessed letter has a positive count in `remaining`, mark it with `{}` and decrement the count, otherwise mark it with `()`. For `wally` and `lalal`, this ensures the available A and L occurrences are consumed only once and produces the correct combination of exact, misplaced, and absent results.

MellowPine42 -

That explains the issue: I was modifying `answer` and then using the modified string for later position checks. I’ll separate the comparison data from the display results and process exact matches first.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.