主要的问题是,当我为i = 2
和j = 1
执行print cells[i-1][j]
时,它应该返回1,但它说有0。我想要计算每个细胞的邻域,但这不能正常工作-但它应该能。
我有一个3 x 3的矩阵,添加额外的带零的边以避免离开数组,然后在我的原始区域上有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)
发布于 2018-08-07 01:10:48
您可能应该在helper函数中提取邻居的总和,在该函数中,您可以使用try-except块来避免测试数组的边界:
有些人可能是这样想的:
import numpy as np
MOORE_OFFSETS = [(1, 1), (1, -1), (1, 0), (-1, 0), (-1, 1), (-1, -1), (0, 1), (0, -1)]
def get_moore_neighbors_sum(array_of_arrays, row, col):
sum_neighbors = 0
for neighbor in MOORE_OFFSETS:
dr, dc = neighbor
try:
if row + dr >= 0 and col + dc >= 0:
sum_neighbors += array_of_arrays[row+dr][col+dc]
except IndexError:
continue
return sum_neighbors
array_of_arrays = # a sequence of sequence of your data
rows = len(array_of_arrays)
cols = len(array_of_arrays[0])
for row in range(rows):
for col in range(cols):
sum_neighbors = get_moore_neighbors_sum(array_of_arrays, row, col)
https://stackoverflow.com/questions/51712398
复制相似问题