I have one question regarding this hangman program of mine.When I guess the a letter(‘o’) right of a word(“good”) which has duplicates,it’s being unveiled only for the first index as list.index(value) returns only one index even if there are duplicates of that value.What do I need to change or add if I want to unveil all the duplicate letters at the same time.
Here’s what I Expect the program to do:
Guess the letter: l >>> _oo_
Thanks.
the_word="good"
#print the_word
wLen=len(the_word)
u='_'*wLen
counter=0
while counter!=12 and wLen!=0:
counter=counter+1
print u
g=raw_input("Guess the letter: ")
p=list(the_word)
x1=the_word.find(g)
if x1 >=0:
u1=list(u)
u1[x1]=g
u=''.join(u1)
wLen=wLen-1
if wLen==0:
print "Congratulation!!!you have guessed the word"
print "The word was",the_word
else:
print "sorry u loose"
In case this is for an assignment, I’ll focus on a simpler solution that will hopefully make sense. You know your target word, and from that you can use a function called
enumerateto find the index positions of all of the letters:So knowing this, let’s say a user inputs
o. Our current ‘guessing’ string looks like____, and we know that we need to replace index positions 1 and 2 witho. Since the guess string and the target word have the same length (since they are supposed to be the same word), one simple solution would be to iterate over the actual word with enumerate, and if the letter iso(or whatever they guessed), replace the same index position in theguessingword with that letter. For example: