I’m really new to python and trying to build a Hangman Game for practice.
I’m using Python 3.6.1
The User can enter a letter and I want to tell him if there is any occurrence of that letter in the word and where it is.
I get the total number of occurrences by using
occurrences = currentWord.count(guess)
firstLetterIndex = (currentWord.find(guess)), to get the index.
Now I have the index of the first Letter, but what if the word has this letter multiple times?
secondLetterIndex = (currentWord.find(guess[firstLetterIndex, currentWordlength])), but that doesn’t work.
Is there a better way to do this? Maybe a build in function i can’t find?
One way to do this is to find the indices using list comprehension:
currentWord = "hello" guess = "l" occurrences = currentWord.count(guess) indices = [i for i, a in enumerate(currentWord) if a == guess] print indices
I would maintain a second list of Booleans indicating which letters have been correctly matched.
>>> word_to_guess = "thicket" >>> matched = [False for c in word_to_guess] >>> for guess in "te": ... matched = [m or (guess == c) for m, c in zip(matched, word_to_guess)] ... print(list(zip(matched, word_to_guess))) ... [(True, 't'), (False, 'h'), (False, 'i'), (False, 'c'), (False, 'k'), (False, 'e'), (True, 't')] [(True, 't'), (False, 'h'), (False, 'i'), (False, 'c'), (False, 'k'), (True, 'e'), (True, 't')]
def findall(sub, s) : pos = -1 hits= while (pos := s.find(sub,pos+1)) > -1 : hits.append(pos) return hits