0

I'm a beginner at python and I was trying to write a program to guess the letters in a word, (here I used 'coconut' ). There is no limitation for guesses. If the guess was correct each time, I want to display the position of the letter as another ( 'guess_map').

So I defined the list guess_map with same length of the word. Then using for loop I was checking the guessed input with the word and replacing the corresponding element in the list 'guess_map'.

But then I found its not working for the letters which are repeating. For example 'c'. The code is just considering the first 'c' in the word. I don't know where I have committed mistake. Can anyone help?

word = 'coconut'
reference = list(word)
number_letters = len(reference)
guess_map = ['-']*number_letters

guess = input('Guess the letter')
for let in reference:
    if let == guess:
        ref_ind = reference.index(let)
        guess_map[ref_ind] = guess

print(guess_map)
quamrana
  • 37,849
  • 12
  • 53
  • 71
Arjun Pankaj
  • 13
  • 1
  • 3
  • Does this answer your question? [How to find all occurrences of a substring?](https://stackoverflow.com/questions/4664850/how-to-find-all-occurrences-of-a-substring) – B. Go Mar 27 '20 at 17:14

1 Answers1

2

The mistake is in ref_ind = reference.index(let). This will only ever find the first occurrence, even though the loop finds all of them.

This version of your program uses enumerate to give you the right index every time.

word = 'coconut'
reference = list(word)
final = reference[:]
number_letters = len(reference)
guess_map = ['-']*number_letters


while guess_map != final:
    guess = input('Guess the letter')
    for ref_ind, let in enumerate(reference):
        if let == guess:
            guess_map[ref_ind] = guess

    print(guess_map)

print("Done")

I've taken the liberty of adding a loop which keeps you guessing until you get it right.

quamrana
  • 37,849
  • 12
  • 53
  • 71
  • While this wasn't a stipulation from the OP, guesses that are the correct letter, but different case will not be accepted. You can change this behavior by using `str.casefold` in your comparisons, and appending `let` instead of `guess` to `guess_map`. – Hampus Larsson Mar 27 '20 at 16:19
  • Yes, I have also tried: `guess = input('Guess the letter').lower()` – quamrana Mar 27 '20 at 16:20
  • Thank you so much. I got it. But i didn't understand 'while guess_map != final:' this line. – Arjun Pankaj Mar 27 '20 at 16:32
  • Sorry, `final` is not a keyword. I added `final = reference[:]` to easily check when the user had finished. – quamrana Mar 27 '20 at 16:36
  • yeah i got it. You defined 'final' above. Thanks ! – Arjun Pankaj Mar 27 '20 at 16:40