Skip to content
Advertisement

Compare two strings, count letters in the right position, then count letters contained in word but in wrong position

I’m working on a game where the computer picks a random word from a list. The user then guess the word from input. The application shall then return +1 for every letter in the correct position and +1 for any letter in the word but not in the correct position. It should only count the letter in the right position once and should not be duplicated when it checks if the letter is in the word. This is my code so far:

def comparison(self) :
    word_letters = []
    guess_letters = []
    correct_position = 0
    correct_letter = 0

    for l in self.guess :
        guess_letters.append(l)

    for l in self.word :
        word_letters.append(l)

    i = 0
    for l in word_letters :
        if l == guess_letters[i] :
            guess_letters.pop(i)
            correct_position += 1
            i -= 1

        i += 1

    for l in guess_letters :
        if l in word_letters :
            correct_letter += 1

    print(
        f"{correct_position} letters in correct position, {correct_letter} correct letters in wrong position.")

This works decently, but encounters problems if the randomly chosen word has duplicate letters. Also I’m interested in finding a way to solve this that isn’t as cluttered as the above code.

I’ve found some solutions through googling, but they only seem to tackle either checking for positions or checking if a letter is contained in a word, and I’ve had a hard time trying to combine the two without ending up with duplicate +1s.

Advertisement

Answer

If I understood your description correctly, this function should do the job:

def comparison(self):
    correct_position = 0
    correct_letter = 0

    for i,l in enumerate(self.guess):
        if l==self.word[i]:
            correct_position+=1
        elif l in self.word:
            correct_letter+=1

    print(
        f"{correct_position} letters in correct position, {correct_letter} correct letters in wrong position.")
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement