Reputation: 11
Following the principles of wordle, each guess is checked and a five letter output is given. G represents green for letters that are the same and in the right place, yellow for letters that the same in the wrong place, and B for no matches.
def output_guess(guess:str, word: str, dictionary: list):
"""
Checks guess for game errors, and outputs current "score" to user
parameters: user's guess, word from dictionary, dictionary
return: none
"""
output = ""
if len(guess) == 5 and guess in dictionary:
for i in range(len(word)):
if guess[i] == word[i]:
output += "G"
elif guess[i] in word:
output += "Y"
else:
output += "B"
else:
print("Word not found in dictionary. Enter a five-letter english word.", end = "")
print(output)
If the answer for example were the five letter word eerie, I would want to receive these outputs for the following guesses:
Guess 1: epees GBYYB
Guess 2: peeve BGYBG
Guess 3: order BYBYB
Guess 4: eerie GGGGG
All of my guesses for my code receive the correct output aside from Guess 3. For Guess 3: order, I get BYBYY instead of BYBYB.
Upvotes: 0
Views: 397
Reputation: 25490
Your logic is incorrect. It is not sufficient to check simply that the character exists in the word, you also need to count the characters in the input and make sure there are an equal or smaller number in the word
import collections
word = "eerie"
guess = "order"
word_counts = collections.Counter(word) # Count characters in the word
guess_counts = collections.defaultdict(int) # Create an empty dict to count characters in guess
output = []
for g, w in zip(guess, word):
guess_counts[g] += 1 # Add to count of current character
if g == w:
# Correct character, correct position
output += "G"
elif guess_counts[g] <= word_counts[g]:
# The minimum that `guess_counts[g]` can be is 1
# Why? We set it in the first line of this loop
# For this condition to be true, word_counts[g] must be > 0
# (i.e `word` must contain `g`)
# And we must have seen `g` fewer (or equal) times than
# the word contains `g`
output += "Y"
else:
output += "B"
print(output)
I used collections.Counter
instead of manually counting the letters, and collections.defaultdict(int)
so I don't need to check if the dict contains the character before incrementing it.
Upvotes: 1