Okay, so I am stuck at this part in my code. When I want the letter that the user guesses to replace that letter in the string of underscores, it replaces every single letter with that letter. I don't know what to do. Here is the code.
def hangman(secret):
'''
'''
guessCount = 7
w = '_'*len(secret)
while guessCount > 0:
guess = input('Guess: ')
if guess in secret:
indices = indexes(secret, guess)
print(indices)
for i in range(len(indices)):
w = w.replace(w[indices[i]],secret[indices[i]])
print(w)
else:
guessCount = guessCount - 1
print('Incorrect.',guessCount,'incorrect guesses remaining.')
Any help in pointing out what I can do specifically in line 9 and 10 would be greatly appreciated.
Here is the first function that I defined earlier that I use in this function.
def indexes(word, letter):
'''returns a list of indexes at which character letter appears in word'
'''
indices = []
for i in range(len(word)):
if letter in word[i]:
indices.append(i)
return indices
Strings are immutable in Python. Hence, it is not a suitable data structure for representing your word. In my opinion, Kyle Friedline's approach is probably the right way.
def hangman(secret, guessCount=7):
assert guessCount > 0 # Never really good to hard code magic numbers.
w = ['_'] * len(secret) # Make 'w' a list instead because list is mutable
while guessCount > 0:
guess = input("Guess: ")
if guess in secret:
indices = indexes(secret, guess) # I'm guessing indexes is defined elsewhere?
for i in indices:
w[i] = guess # Make it explicit. secret[i] == guess anyway.
print("".join(w)) # Join w into a word
else:
guessCount -= 1 # More concise
print("Incorrect. ", guessCount, " incorrect guesses remaining.")
A little suggestion for implementing indexes:
def indexes(word, letter):
return [i for i, c in enumerate(word) if c == letter]
Or simply replace the call to indexes()
with:
indices = [i for i, c in enumerate(secret) if c == guess]
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments