For a school project I have to create a wordle in Python. The program I created compares the letters of the target word and the guessed word. An example: the target word is "compulsory" and the guessed word is "submission". The output should be "-O-O--X-O-".
"X" meaning the letter in the guessed word is also in the target word and is at the same spot. "O" meaning the letter in the guessed word is also in the target word but isn't at the same spot. "-" means that it's the wrong letter.
But I can't seem to find a way to cope with duplicate letters. For example, if the target word is "teethe" and the guessed word is "health" it should give me the output: "OX--O-". Though my program returns the output: "OX--OO".
My code:
def compare(guess, target):
output = ""
for i in range(target.__len__()):
if guess[i] == target[i]:
output = output + "X"
elif guess[i] in target:
output = output + "O"
else:
output = output + "-"
return output
print(compare("health", "teethe"))
I hope I provided enough information for you to understand my question/problem.
Thank you in advance for your help!
This took me a while to solve, but I got it I think.
Here's the solution the way I implemented it:
def compare(guess: str, target: str):
output = ["-"] * len(target)
for index, (guess_letter, target_letter) in enumerate(zip(guess, target)):
if guess_letter == target_letter:
output[index] = "X"
target = target.replace(guess_letter, "-", 1)
for index, (guess_letter, target_letter) in enumerate(zip(guess, target)):
if guess_letter in target and output[index] == "-":
output[index] = "O"
target = target.replace(guess_letter, "-", 1)
return ''.join(output)
print(compare('health', 'teethe'))
print(compare('submission', 'compulsory'))
Here's an identical solution that uses simpler (but less "Pythonic") tools:
def compare(guess, target):
length = len(target)
output = ["-"] * length
for index in range(length):
if guess[index] == target[index]:
output[index] = "X"
target = target.replace(guess[index], "-", 1)
for index in range(length):
if guess[index] in target and output[index] == "-":
output[index] = "O"
target = target.replace(guess[index], "-", 1)
return ''.join(output)
print(compare('health', 'teethe'))
print(compare('submission', 'compulsory'))
Output:
OX--O-
-O-O--X-O-
Here are my key techniques:
'X'
. I'm initially maintaining this as a list, then converting it to a string when returning.'-'
.'X'
) first.