【问题标题】:Compare two lists in Python on equality and positioning比较 Python 中关于相等和定位的两个列表
【发布时间】:2020-04-09 05:36:02
【问题描述】:

我正在开发经典游戏Mastermind 的可玩版本作为一个爱好项目,我需要能够比较两个字符串列表(一个是猜测,另一个是代码)并获得数字和应该显示为反馈的“钉子”的颜色。

基本上,对于相同颜色和相同位置的两个钉子,会显示一个红色钉子。对于两个不同位置的相同颜色的钉子,将显示一个白色钉子。然而,一个白色的钉子必须匹配两个特定的钉子(例如 Guess = [Green, Green, Green, Blue],Code = [Yellow, Yellow, Green, Green] 将导致显示一个红色和一个白色的钉子)。

我发现了许多关于仅位置或仅相等性比较的帖子,但我需要一种将两者都考虑在内的算法。到目前为止,这是我的代码:

def getResponse(guess, code):
    pegs = []
    usedIndices = []
    usedCodeIndices = []
    for x in range(len(guess)):
        if guess[x] == code[x]:
            usedIndices.append(x)
            usedCodeIndices.append(x)
            pegs.append("red")
        elif guess[x] in code and x not in usedIndices:
            usedIndices.append(x)
            usedCodeIndices.append(code.index(guess[x]))
            pegs.append("white")
    return pegs

此代码适用于红色钉子,但无法识别重复项并显示太多白色钉子(例如 Guess = [Blue, Blue, Blue, Blue], Code = [Blue, Red, Blue, White] 会导致显示了两个红色钉子和两个白色钉子,尽管应该只显示两个红色钉子。

【问题讨论】:

  • 你有什么问题?
  • 使用zip函数
  • for i, in zip (list_a, list_b): ,您可以从两个列表的单个循环中访问相同的索引元素。
  • @KlausD。见最后一段。

标签: python python-3.x


【解决方案1】:

您可以使用 zip 计算位置匹配,使用 Counter 计算整体颜色匹配。然后从颜色匹配计数中减去位置匹配计数:

guess = ["R","R","B","W","Y"]
code  = ["R","G","B","R","Y"]

from collections import Counter
positionMatches = sum(a==b for a,b in zip(guess,code))
colorMatches    = len(code) - sum((Counter(code)-Counter(guess)).values())
colorMatches   -= positionMatches

print(positionMatches,colorMatches) # 3 1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多