Home > Blockchain >  How can I control same items in list
How can I control same items in list

Time:08-24

I'm making hangman in python and it works very simple:

secretWorld=list(input("secretWorld: "))
guess=str(input("guess: "))

if guess in secretWord:
        ind=secretWord.index(guess)
        contl[ind*2]=guess
print(contl)

But this changing underlines works only for the first letter e.g. secretWord="skill" guess="l" I will get _ _ _ l _ and I want _ _ _ l l

CodePudding user response:

Firstly, there's a typo ("secretWorld" / "secretWord").

Secondly, the problem is that the list.index method will only return the first instance of an element in a list. What you want is all of the elements so your code should instead look like this (again, stolen from https://stackoverflow.com/a/6294205/14692938):

secretWord=list(input("secretWord: "))
guess=str(input("guess: "))

if guess in secretWord:
    indices = [i for i, x in enumerate(my_list) if x == guess]
    for ind in indices:
        contl[ind*2]=guess
print(contl)

CodePudding user response:

I'd suggest the following:

secretWord=list("skill")
contl = "".join("_" for _ in range(len(secretWord)))

guess=str("k")

contl = [guess if c == guess else contl[idx] for idx, c in enumerate(secretWord)]
print(contl) # ['_', 'k', '_', '_', '_']

guess=str("l")

contl = [guess if c == guess else contl[idx] for idx, c in enumerate(secretWord)]
print(contl) # ['_', 'k', '_', 'l', 'l']

It recreates contl with each guess, replacing all the underscores matching with guess, otherwise leaving contl as it is.

CodePudding user response:

You can try this method. I just used for loop to go through all the letters

secretWord = "skill"
userInput = "l"
secretText = "_"*len(secretWord)

if userInput in secretWord:
    for i in range(len(secretText)):
        if secretWord[i] == userInput:
            secretText = secretText[:i]   userInput   secretText[i 1:]

print(secretText)

Output:

___ll

This is assuming that there is no whitespace and all letters are lowercased.

CodePudding user response:

You can use list comprehension and loop through all the char in the secretWord.

[i for i, c in enumerate(secretWord) if c == char]

Or build a char to index dictionary from secretWord and lookup from it.

from collections import defaultdict

char_to_idx = defaultdict(list)
for i, c in enumerate(secretWord):
    char_to_idx[c].append(i)

CodePudding user response:

And another way to do it, using re.finditer.

import re

secretWord=input("secretWord: ")
guess=input("guess: ")
contl = list(''.ljust(len(secretWord), '_'))

for match in re.finditer(guess, secretWord):
    contl[match.start():match.end()] = guess

print(''.join(contl))
  • Related