Home > Back-end >  'Renaming' duplicate items in a Python list
'Renaming' duplicate items in a Python list

Time:02-08

I am creating a word guessing game where a player needs to guess the secret word.

For each guess the user makes, I classify each letter of a guess to either of the following three categories:

Hot - The letter is in the right place when compared to the secret word.
Warm - The letter is in the secret word but not in the right place.
Cold - The letter is not in the secret word.

To do this, I have created a simple loop:

for i in range(len(guess)):
    if guess[i] in secret_word[i]:
        # Hot
    elif guess[i] in secret_word:
        # Warm
    else:
        # Cold

However, the problem with this loop is, for instance, the secret word is: apple, and the user inputs puppy. The loop returns:

Hot: [p]
Warm: [p, p]
Cold: [u, y]

The error(s):
1. We don't know which 'p' are the right/wrong ones.
So to fix this, I was planning to 'assign' them numbers corresponding to how many times they appear in the guess so that the output should be like below:

Hot = [p2]
Warm = [p1] # Since there are 2 remaining 'p's, we'll just take the first one
Cold = [p3, u, y]

This way, the user knows which letter and position they got right. Although, I have been trying to implement the above procedure in my code to no avail. I'll be really grateful if anyone can help me!

CodePudding user response:

You can achieve this easier by using enumerate. This way you can access both index and letter and quickly compute if a letter is hot, warm or cold. Something like this:

secret = "apple"
guess = "puppy"

hot = []
warm = []
cold = []

for index, letter in enumerate(guess):
    if letter == secret[index]:
        hot.append(letter   str(index))
    elif letter in secret:
        warm.append(letter)
    else:
        cold.append(letter)

print(f"Hot: {hot};  Warm: {warm}; Cold: {cold}")

For your example this will output:

Hot: ['p2'];  Warm: ['p', 'p']; Cold: ['u', 'y']
  •  Tags:  
  • Related