def neighbors(matrix, r, c):
live_neighbors = 0
if matrix[r][c-1] != 0:
live_neighbors += 1
if matrix[r-1][c] != 0:
live_neighbors += 1
if matrix[r-1][c+1] != 0:
live_neighbors += 1
if matrix[r][c-1] != 0:
live_neighbors += 1
if matrix[r][c+1] != 0:
live_neighbors += 1
if matrix[r+1][c-1] != 0:
live_neighbors += 1
if matrix[r+1][c] != 0:
live_neighbors += 1
if matrix[r+1][c+1] != 0:
live_neighbors += 1
return live_neighbors
这是我目前编写的代码。如何计算边界单元格的邻居数量?如果使用此代码,将会出现一个索引超出范围的错误。
scipy.signal.convolve
也很有用。 - Brad Solomon