主要问题是当我print cells[i-1][j]
for i = 2
和j = 1
时,它应该返回1,但是它说有0。我想计算每个单元的邻域数,但这不能正常工作,但应该这样做。在
我有一个3x3矩阵,添加额外的零边以避免数组外,然后在我的原始区域上有2个for循环,用值来计算邻域。但是这个计数被打破了。在
import numpy as np
def get_generation(cells, generations):
cells=np.array(cells)
for k in range(generations):
cells=np.c_[np.zeros(cells.shape[0]), cells,np.zeros(cells.shape[0])]
cells=np.r_[[np.zeros(cells.shape[1])], cells, np.zeros(cells.shape[1])]]
for i in range(1, cells.shape[0]-1): #vertical
for j in range(1, cells.shape[1]-1): #horizontal
neighbours=0
neighbours+=sum(cells[i-1][j-1:j+2])
print neighbors, cells[i-1][j-1], cells[i-1][j], cells[i-1][j+1]
print i, j
neighbours+=sum(cells[i+1][j-1:j+2])
neighbours+=cells[i][j-1]
neighbours+=cells[i][j+1]
return cells
start = [[1,0,0],
[0,1,1],
[1,1,0]]
get_generation(start, 1)
您可能应该在helper函数中提取邻域的总和,在该函数中可以使用try except块来避免测试数组的边界:
有人这样想,也许:
相关问题 更多 >
编程相关推荐