我需要编写一个函数def amountofNeighbours(row, column)
来打印矩阵中某个元素的邻居数量。例如,给定矩阵[[2, 3, 4], [5, 6, 7], [8, 9, 10]]
,位置[0] [0]处的元素2有三个邻居,而位置[1] [1]处的元素6有八个邻居。我不确定处理这类问题的最佳方法是什么。我经历了所有可能性,这给了我以下内容:
def amountofNeighbours(row, column):
neighbours = 0
for i in range(row):
for j in range(column):
if i == 0 and j == 0 or i == 0 and j == column - 1:
neighbours = 3
elif i == row - 1 and j == 0 or i == row-1 and j == column - 1:
neighbours = 3
elif i > 0 and j == 0 or i == 0 and j > 0:
neighbours = 5
elif i == row - 1 and j > 0:
neighbours = 5
elif j == column - 1 and i > 0:
neighbours = 5
else:
neighbours = 8
return neighbours
当我用amountofNeighbours(1, 1)
打电话给它时,它给了我正确答案,即3,但是如果我用amountofNeighbours(2,2)
给它打电话,答案应该是8,而它给了我3.任何人都有一个想法改进?
答案 0 :(得分:4)
一个直接的方法是说,“如果单元格在拐角处,它有三个邻居,否则如果它在边缘,它有五个,否则它有8个。”
def numberOfNeighbors(rows, columns, row, column):
topBottom = row in (0, rows-1)
leftRight = column in (0, columns-1)
if topBottom and leftRight:
return 3
if topBottom or leftRight:
return 5
return 8
答案 1 :(得分:1)
现在设计的功能不符合您的指定。它包含行数和列数。然后它遍历矩阵的所有元素并计算邻居的数量。然后它返回最后计算的值,所以矩阵的右下角元素确实有3个邻居。
你应该摆脱循环,让它做你想要的。澄清:
def amountofNeighbours(row, column, n_rows, n_cols):
neighbours = 0
if row == 0 and column == 0 or row == 0 and column == n_cols - 1:
neighbours = 3
elif row == n_rows - 1 and column == 0 or row == n_rows-1 and column == n_cols - 1:
neighbours = 3
elif row > 0 and column == 0 or row == 0 and column > 0:
neighbours = 5
elif row == n_rows - 1 and column > 0:
neighbours = 5
elif column == n_cols - 1 and row > 0:
neighbours = 5
else:
neighbours = 8
return neighbours
答案 2 :(得分:0)