how to replace all the coincident elements of a list to another

Question:

I’m trying to make a hangman game, and I got a problem. When I try to check if a letter is in the chosen word, it won’t work if there are two or more same letters. For example the word is WINDOW. If I choose the W as the guessing letter, it will only put the first one W, and if I try to guess W again, it will go to the first place again. I’m gonna leave the code below.

index = ANSWER.index(GUESTWORD)
            BOARD[int(index)] = GUESTWORD
print(BOARD)

OUTPUT

> ['W', 'I', 'N', 'D', 'O', '__']

I tried all I could but I can’t get the W to fill the both spaces at the same time.
Thanks!!

Asked By: Brosa Jan

||

Answers:

ANSWER.index(GUESTWORD) will always give you the first index of GUESTWORD in ANSWER. What you want to do is iterate over all the occurrences. For example:

for i, c in enumerate(ANSWER):
    if c == GUESTWORD:
        board[i] = GUESTWORD
Answered By: Samwise

You can use a list comprehension to rebuild the pattern of found letters (board) without the need to manipulate indexes:

ANSWER  = "WINDOWS"

FOUND  = "_"*len(ANSWER)

while "_" in FOUND:
    print(*FOUND)
    FOUND  = *FOUND,*input("guess: ").upper()
    FOUND  = [a if a in FOUND else "_" for a in ANSWER]    

print(*ANSWER)
print("Success!!!")

output:

_ _ _ _ _ _ _
guess: w
W _ _ _ _ W _
guess: a
W _ _ _ _ W _
guess: i
W I _ _ _ W _
guess: f
W I _ _ _ W _
guess: n
W I N _ _ W _
guess: d
W I N D _ W _
guess: s
W I N D _ W S
guess: o
W I N D O W S
Success!!!

Allows multiple letters in guess:

_ _ _ _ _ _ _
guess: w
W _ _ _ _ W _
guess: g
W _ _ _ _ W _
guess: i
W I _ _ _ W _
guess: ndo
W I N D O W _
guess: s
W I N D O W S
Success!!!

You may also use a set for the guessed letters which would avoid having a variable (FOUND) that continually changes type (from string to tuple to list):

ANSWER  = "WINDOWS"

GUESSES = set()

while not GUESSES.issuperset(ANSWER):
    print(*[a if a in GUESSES else "_" for a in ANSWER])
    GUESSES.update(input("guess: ").upper())
    
print(*ANSWER)
print("Success!!!")
Answered By: Alain T.
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.