【问题标题】:Best way to find all indexes in a string then using the indexes to edit letters at those positions in another string for Hangman Game查找字符串中所有索引的最佳方法,然后使用索引在 Hangman Game 的另一个字符串中编辑这些位置的字母
【发布时间】:2020-09-08 10:59:13
【问题描述】:

我在制作刽子手游戏的过程中陷入了困境:
对于具有多个相同字母的单词,我希望程序将用户输入与单词相匹配,然后显示该字母的所有实例(就像在常规 Hangman 中一样)。
我创建了目标单词的副本并将所有字母替换为 #,然后每当用户发现复制“隐藏”版本的字母随着字母的发现而缓慢变化时,它适用于单个字母实例,但不适用于多个字母。
以下代码不可运行,因为第 24-29 行需要更改。
我了解了使用 def() 函数来帮助从字符串中提取多个索引,但是它们存储在一个列表中,我不知道如何以这种格式使用它们。我还不擅长 for 循环。

所以 TL;DR:第 24-29 行需要更改,以便找到所有相同的字母实例,然后使用这些索引更改隐藏的单词以发现所有找到的字母供用户查看。

 def change_char(s, p, r):
    return s[:p]+r+s[p+1:]

def find(s, ch):
    return [i for i, ltr in enumerate(s) if ltr == ch]
word = "abigail" #Test Word to be guessed
edited_word = word.replace(word,  "#" * len(word)) #making the second copy hidden
guessed_word = edited_word #copied word for uncovering attempt
win = 0
guess = 0
guesses_left = len(word)
print("Good luck! You have {} guesses left. Press ! to quit".format(guesses_left))
print(edited_word)
while win == 0:
    guess = input()
    if len(guess) >= 2: # checking for single inputs only
        print("Valid inputs only! 1 character per guess, no numbers or symbols. Press ! to quit")
        continue
    elif "!" in guess: # checking if user wants to quit
        break
    elif guess.isnumeric(): # checking for numbers
        print("Valid inputs only! 1 character per guess, no numbers or symbols. Press ! to quit")
        continue
    elif word.find(guess) != -1: # if character exists will return index, user guessed a character right!
        # found_letter_index = word.find(guess) |||| this was my original code, it only wqorked with single letter instances
        found_letter_index = find(word, guess) # new attempt that returns indexes but are stored in a  list
        found_letter = word[found_letter_index]
        guessed_word = change_char(guessed_word, found_letter_index, found_letter)
        print("test {}".format(guessed_word)) #test print for trouble shooting
    elif word.find(guess) == -1: # user guessed character wrong
        guesses_left -= 1
        print("Guesses Left: {}".format(guesses_left))
    elif guesses_left == 0: # failed too many times, game exits
        print("You loose, no more guesses left!")
        break

这是一个帮助我了解更多关于 python 的项目,到目前为止,我只是通过谷歌搜索和阅读 python 文档来完成它,所以如果你能提供一个解释和你的答案,我们将不胜感激并极大地帮助我!
提前致谢。

【问题讨论】:

    标签: python-3.x for-loop indexing


    【解决方案1】:

    使用以单个字母填充的字典作为键及其位置列表。 使用'#' 列表作为提示提供者,如果猜到了好消息,则替换正确的位置。您不想一直进行字符串切片,因为字符串是不可变的,并且一直被丢弃/重新创建。列表可以更改索引位置的内容,而无需重新创建/删除。

    优点是您只需迭代单词两次(如果您使用 defaultdict(list) 一次) - 所有其他“查找”操作都是简单的查找,根本不需要时间。

    可能是这样的:

    word = "guessme"
    
    # create a dictionary with key:list inputs, use a defaultdict(list) for bonus points
    letter_pos = {l:[] for l in word}
    
    # fill the list with the positions
    for idx,l in enumerate(word):
        letter_pos[l].append(idx)
    
    # create list with a # for each letter
    guessed = ['#' for _ in word]
    
    auto_guess = "qetusmglr"
    
    print(f"Hint: {''.join(guessed)}")
    
    # you need a while True here and the input() mechanics from above
    for g in auto_guess:
        print(f"Your guess: {g}") 
    
        # letter in our dict with positions? 
        if g in letter_pos:
            # iterate all positiones in the list and replace with letter
            for idx in letter_pos[g]:
                guessed[idx] = g
            # delete the letter from the dict
            del letter_pos[g]       
    
        # use ''.join( ... )  to print the list as string 
        print(f"Found: {''.join(guessed)}")
    
        # empty dictionary == all letters found
        if not letter_pos:
            break
    
    print("Done")
    

    输出:

    Hint: #######
    Your guess: q
    Found: #######
    Your guess: e
    Found: ##e###e
    Your guess: t
    Found: ##e###e
    Your guess: u
    Found: #ue###e
    Your guess: s
    Found: #uess#e
    Your guess: m
    Found: #uessme
    Your guess: g
    Found: guessme
    Done
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-19
      • 2018-10-03
      • 2012-03-23
      相关资源
      最近更新 更多