生命的矩阵康威游戏中的邻居计数



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

从我的初始阵列开始

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

我的结果应该是:

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

我创建了一个函数,并使用蛮力方法来查找细胞周围是否存在。如果是,请将值相加并返回总数。我不确定我是否正确地处理了if语句。它说以下错误

'具有多个元素的数组的真值不明确:请使用.any()或.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)

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

尝试scipy.signal.convolve2d类似的东西

convolve2d( yourMatrix, np.ones((3,3))

应该做的技巧

关于您的代码:您可能不太熟悉Python或numpy语法,所以我建议您找一些教程来练习基础知识。如果整列中有任何细胞存活,则(board[column - 1]).any()将为True,反之为False。之后,您将测试板内是否包含True(或False,如果列中的所有单元格都已死亡),该值将始终为True。所以你的if语句没有多大意义。

要测试邻居中的一个细胞是否存活,它看起来像以下任何if语句:

if board[row-1][column - 1]  ==  1:
if board[row-1, column - 1]   ==  1: 
if board[row-1, column - 1] : #in Python 1 is True and 0 is False

也就是说,要计算一个点周围的活细胞数量,你根本不应该使用if语句,只需将周围的所有值相加,一个死细胞值0,一个活细胞值1,所以无论如何只有活细胞会出现在计数中。更进一步,你的代码会非常慢,你永远不应该使用for循环来迭代numpy数组,正确的做法是利用所谓的矢量化操作,即一次应用于整个数组的操作,例如:board[:,1:]+board[:,:-1]将为您提供一个数组,该数组包含可以计算该和的每个单元格的和(左侧单元格+右侧单元格)。

最新更新