RJB RJB - 1 year ago 56
Python Question

2 occurrences of a letter not spotted by indexing

I am creating a game of hangman in python 3 and all seems to be working well apart from one part of the game. Take for example, the word 'hello'. Hello contains two 'l's. My game does not recognise that you can have more than one occurrence of a letter in a word and therefore does not update the game as it should. Here is how the program runs -
When entering 'L'

The number of times L occured was 2
('WORD:', 'HEL*O', '; you have ', 10, 'lives left')
Please input a letter:

(btw I am aware the print is messy and I havent got round to sorting that yet lol)

as you can see, 'L' only allows me to get the one L in Hello and not all of them as you would expect in a game of hangman.

Here is my code for the part where the game is updated:

def updateGame (x, charStr) :
occ = x['secWord'].count(charStr)
charCount = 0
indcount = 0
if charStr in x['secWord']:
while occ > charCount :
pos = x['secWord'].index(charStr, indcount)
x['curGuess'][pos] = charStr
indcount = indcount + 1
charCount = charCount + 1
else :
x['livesRem'] = x['livesRem'] - 1
return occ

What do I do here to make it so that both letters are updated when a letter is guessed correctly? I tried a solution from a previous question and it did not work as it didnt update the letters in the curGuess part of the dictionary: How to use index in a while loop which finds the next occurrence each time - This may well be nearly the answer to my question but I simply could not get it to work!

More info:

  • x is a dictionary

  • charStr is a single character string

  • I tried to use indcount to shift where the index was read from but this did not work either

Thanks a lot in advance for any help that is given, it is much appreciated!

Answer Source

I think you're also misunderstanding the second parameter of index, which is the start index to search from, not the nth occurrence to look for. What's happening right now is you're replacing the first "L" twice.

string.index(s, sub[, start[, end]])
    Like find() but raise ValueError when the substring is not found.

Where find says that:

Return the lowest index in s where the substring sub is found such that sub is wholly contained in s[start:end].

So, you don't need the indcount variable, which is the nth L to find, you need the position of the last found L, plus 1. Replace "indcount" with "pos + 1" so that it searches past the last found occurrence of the letter, and it should work as intended.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download