how to replace item in a list with two indexes

Viewed 135

I'm a beginner in python and I am trying to make a hangman game but I can't seem to get it to work. Here's my code:

word = "street"
letters = list(word)
dashes = ["_","_","_","_","_","_"]
guess = input("Guess the letter. ") #assuming that "e" was the input
x = [index for index, value in enumerate(letters) if value == guess]
dashes[x] = guess

I want to replace in dashes in dashes that have the indexes in x. In the case of "e" being the input that means dashes[3] and dashes[4] become "e". dashes[x] = guess doesn't seem to work.

5 Answers

It's easier to build a new list dashes and reassign the name after each guess than to maintain a list of dashes which you mutate.

Demo:

>>> word = 'street'
>>> dashes = ['_']*len(word)
>>> 
>>> guess = 'e'
>>> dashes = [guess if letter == guess else current
...:          for letter, current in zip(word, dashes)]
>>> dashes
>>> ['_', '_', '_', 'e', 'e', '_']
>>> 
>>> guess = 't'
>>> dashes = [guess if letter == guess else current
...:          for letter, current in zip(word, dashes)]
>>> dashes
>>> ['_', 't', '_', 'e', 'e', 't']

A direct continuation of the code you already wrote is to loop over the indices in x:

for i in x:
   dashes[i] = guess

Alternatively, you could combine the list comprehension and the loop:

for i in range(len(word)):
    if dashes[i] == '_' and word[i] == guess:
        dashes[i] = guess

Personally, I use NumPy a lot and feel that's it's a pretty good fit for this problem:

import numpy as np
word = np.array(list("street"))
dashes = np.full_like(word, "_")
guess = input("Guess the letter. ")
dashes[word == guess] = guess

No Python loops, just vectorized computation. :)

Or list comprehension:

print([v if i not in x else guess for i,v in enumerate(dashes)])

Here is a complete solution:

word = "street"
guessed = "_" * len(word)
attempts = 0
while '_' in guessed:
    guess = input("Guess the letter:: \n> ")
    guessed = [x if guess != letter else guess for letter, x in zip(word, guessed)]
    print(' '.join(guessed))
    attempts += 1
    if attempts > 7:
        print('Too many wrong guesses.. You lose.')
        break
else:
    print('CONGRATULATIONS!')
word = "street"
dashes = ['_'] * len(word)

guess = raw_input("Guess the letter. ")

dashes = map(lambda x: x if x == guess else '_', word)

map applies a function to every element of a list. lambda is a nameless function.

Related