首页 > 解决方案 > Python - 行矩阵中的 4 个 - 变量不会改变

问题描述

正如您可能知道连续 4 枚硬币一样,您需要连续拥有 4 枚相同的硬币。硬币由 1 和 2 表示。0 只是一个占位符,因此如果存在一行多个零,则没有一个占位符。所以我完成了我的代码以垂直穿过矩阵。现在剩下的是水平和对角线。但是我很难完成我的垂直代码。我调试它并多次重写它,但我无法让它工作。那是我的工作代码,它垂直穿过矩阵。

# using this matrix to test
# I know this is not a possible cobination in 4 in a row
# but its easier to test like that
matrix = [
    [2, 2, 2, 2, 0, 0, 0],
    [2, 1, 1, 1, 1, 1, 0],
    [2, 0, 0, 0, 0, 0, 0],
    [2, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 1, 1, 1, 1],
]
def WhoWon(self, matrix = True):
    if matrix == True:
        matrix = self.matrix
    for line in matrix:
        last = 0
        count = 0
        for x in line:
            isPlayer = x == 1 or x == 2
            if isPlayer and last == x:
                count += 1
                if count == 4:
                    return x
            elif isPlayer:
                count = 1
                last = x
            else:
                count = 0
                last = 0

这是我的垂直槽矩阵代码(似乎 last 由于某种原因没有改变):

for i in range(len(matrix[0])):
    for i2 in range(len(matrix)):
        last = 0
        count = 0
        x = matrix[i2][i]
        isPlayer = x == 1 or x == 2
        if isPlayer and last == x:
            count += 1
            if count == 4:
                return x
        elif isPlayer:
            count = 1
            last = x
        else:
            count = 0
            last = 0

所以也许有人可以帮助我,我也不知道如何对角线穿过矩阵,所以欢迎提出想法。提前致谢。

标签: pythonlistmatrix

解决方案


对于您在垂直方面遇到的问题:当您获得该列的下一个值时,您将lastand设置count为。0这应该有效:

for i in range(len(matrix[0])):
    last = 0  #only reset when starting next column
    count = 0 #only reset when starting next column
    for i2 in range(len(matrix)):
        # last = 0  #< delete it here
        # count = 0 #< delete it here
        x = matrix[i2][i]
        isPlayer = x == 1 or x == 2
        if isPlayer and last == x:
            count += 1
            if count == 4:
                return x
        elif isPlayer:
            count = 1
            last = x
        else:
            count = 0
            last = 0

总的来说:python 很棒,但对于矩阵本身来说不是很好。你总是有一个列表列表。因此,我还建议您numpy按照@Alireza 的建议进行调查。它使这项工作变得更加容易!


推荐阅读