python - 计算 Matrix 中的邻居数 - Conway Game of Life

标签 python numpy scipy

对于每个矩阵元素,我想添加其所有相邻单元格的值。

从我的初始数组开始

board = np.array([[0, 1, 1],
                   [0, 1, 0],
                   [1, 0, 0]])

我的结果应该是:

([2,2,2],
 [3,3,3],
 [1,2,1])

我创建了一个函数并使用暴力法来查找其周围是否存在一个单元格。如果是,则将这些值相加并返回总数。我不确定我是否正确处理了我的 if 语句。说的是下面的错误

'具有多个元素的数组的真值不明确:使用 a.any() 或 a.all()'

def count_living_neighbors(board):
    count = np.zeros(board.shape, dtype=int)
    #
    # YOUR CODE HERE
    #

    for row in range(len(board)):
        for column in range(len(board[row])):
            total = 0
            if (board[column - 1]).any() in board:
                total += board[row][column-1]
            if (board[column + 1]).any() in board:
                total += board[row][column+1]    
            if (board[row - 1]).any() in board:
                total += board[row-1][column]
            if (board[row + 1]).any() in board:
                total += board[row+1][column]
            if (board[row + 1] and board[column - 1]).any() in board:
                total += board[row+1][column-1]
            if (board[row - 1] and board[column - 1]).any() in board:
                total += board[row-1][column-1]
            if (board[row + 1] and board[column + 1]).any() in board:
                total += board[row+1][column+1]
            if (board[row - 1] and board[column + 1]).any() in board:
                total += board[row+1][column+1]

            count[row][column] = total         

    return count

最佳答案

您可以将 scipy.signal.convolvemode='same' 一起使用:

from scipy import signal

kernel = np.ones((3, 3), dtype=np.int8)
kernel[1, 1] = 0
print(signal.convolve(board, kernel, mode='same'))
[[2 2 2]
 [3 3 3]
 [1 2 1]]

这里的 kernel 看起来像这样:

array([[1, 1, 1],
       [1, 0, 1],
       [1, 1, 1]], dtype=int8)

并且无论board的形状如何,都是一样的。基本上,kernel 是指邻居的位置(相对于中心的 0)。

关于python - 计算 Matrix 中的邻居数 - Conway Game of Life,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47371787/

相关文章:

python - 生成 3D 高斯数据

python - 如何为 vscode 的数据科学模式设置环境变量?

python - numpy 读取带有复数的 .csv

python - 高级切片 : Given a list of index, 从 numpy 数组中选取不同的元素

python - 为什么使用 Numba 进行矩阵乘法很慢?

python - python 中 scipy 四元集成的问题

python - 通过扩建和最少的停机时间部署到生产环境?

python - 如果失败,几天后重新运行 python 脚本

python - 在 python 云函数中验证 JWT 访问 token 时出现问题

python - scipy中的稀疏矩阵转置