计算矩阵中的邻居 - Conway Game of Life [英] Counting Neighbors in Matrix - Conway Game of Life
问题描述
对于每个矩阵元素,我想添加其所有相邻单元格的值.
For each matrix element, I want to add the values of all its neighbor cells.
从我的初始数组开始
board = np.array([[0, 1, 1],
[0, 1, 0],
[1, 0, 0]])
我的结果应该是:
([2,2,2],
[3,3,3],
[1,2,1])
我创建了一个函数并使用蛮力方法来查找其周围是否存在单元格.如果是,则将这些值相加并返回总数.我不确定我是否正确地处理我的 if 语句.它说以下错误
I created a function and used a brute force method to find whether or not a cell exists in its surrounding. If it does, add up the values and return the total. I'm not sure if I'm approaching my if statements correctly. It's saying the following error
'具有多个元素的数组的真值不明确:使用 a.any() 或 a.all()'
'The truth value of an array with more than one element is ambiguous: Use a.any() or 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.convolve
与 mode='same'
一起使用:
You can use scipy.signal.convolve
with mode='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
看起来像这样:
Here kernel
looks like this:
array([[1, 1, 1],
[1, 0, 1],
[1, 1, 1]], dtype=int8)
并且无论board
的形状如何,都是一样的.基本上,kernel
指的是邻居的位置(相对于中心的 0).
and will be the same regardless of the shape of board
. Basically, kernel
is referring to the positions of the neighbors (relative to the 0 in the center).
这篇关于计算矩阵中的邻居 - Conway Game of Life的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!