Python大师头脑无法使程序返回正确数字和错误数量

2024-04-23 18:25:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我想做一个基于数字列表的策划游戏。这就是我的程序现在的样子

我有一个函数,如果两个列表中的数字在同一索引处相等(trulycorrect),则该函数返回正确位置的数字量

我的问题是,我无法找出一个函数,它返回错误索引中但同时存在于两个列表中的数字量。这意味着用户猜测中的同一个数字

zexampe1:如果我生成的列表=[3,1,3,3],用户猜测[3,3,3] 输出应为。 3在正确的位置0在错误的位置 但我明白了。 3在正确的地方1在错误的地方

示例2:如果我生成的列表=[8,1,1,1],并且用户猜测[8,8,8,8] 输出应为。 1在正确的位置0在错误的位置 但我明白了。 1在正确的地方3在错误的地方

希望你明白我的意思。我是个Python新手


Tags: 函数用户程序游戏示例列表地方错误
1条回答
网友
1楼 · 发布于 2024-04-23 18:25:09

问题出在right_inwrongplace函数中。你需要确保在计算那些正确但在错误的地方的猜测之前忽略了所有正确的猜测。您可以先从列表中删除正确的猜测:

def right_inwrongplace(userGuess, number):
    # Create a list of Boolean values representing correct guesses.
    # for exemple: if numbers = [1,2,3,4] and guess = [1,2,9,9], correct_places will be [True,True,False,False]
    correct_places = [True if v == number[i] else False for i, v in enumerate(userGuess)]
    # create a list with only the incorrect guesses.
    g = [v for  i, v in enumerate(userGuess) if not correct_places[i]]
    # create a list with the numbers which weren't guessed correctly.
    n = [v for  i, v in enumerate(number) if not correct_places[i]]
    #return the amount of guesses that are correct but in the wrong place. (the numbers that are in both lists) 
    return len([i for i in g if i in n])

相关问题 更多 >