Python 计算矩阵中邻域数量的最佳方法?

Python 计算矩阵中邻域数量的最佳方法?,python,matrix,Python,Matrix,我需要编写一个函数defamountofneighbours(行、列),用于打印矩阵中某个元素的邻域数量。例如,给定矩阵[[2,3,4],[5,6,7],[8,9,10],元素2在位置[0][0]处有三个邻居,而元素6在位置[1][1]处有八个邻居。我不确定处理这样的问题最好的方法是什么。我经历了所有的可能性,这给了我以下几点: def amountofNeighbours(row, column): neighbours = 0 for i in range(row):

我需要编写一个函数
defamountofneighbours(行、列)
,用于打印矩阵中某个元素的邻域数量。例如,给定矩阵
[[2,3,4],[5,6,7],[8,9,10]
,元素2在位置[0][0]处有三个邻居,而元素6在位置[1][1]处有八个邻居。我不确定处理这样的问题最好的方法是什么。我经历了所有的可能性,这给了我以下几点:

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。有人有改进的想法吗?

您现在设计的功能没有达到您指定的效果。它接受行和列的数量。然后它循环遍历矩阵的所有元素并计算邻居的数量。然后返回最后计算的值,即矩阵右下角的元素,它确实有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

避免许多IFs的一个解决方案是从元素开始,计算其周围的“放大”框(3x3正方形),可能部分放置在矩阵之外

然后钳制结果并返回元素数减1:

def neighbors(row, col, rows, cols):
    ra, rb = row-1, row+2
    ca, cb = col-1, col+2
    dx = min(cb, cols) - max(0, ca)
    dy = min(rb, rows) - max(0, ra)
    return dx*dy - 1


该图像显示选定元素及其周围的放大框。“最小/最大”操作将切断多余的方块,留下一个2x3框,导致2*3-1=5个邻域计数。

一个直接的方法是说,“如果单元格在拐角处,它有三个邻域,否则如果它在边上,它有五个邻域,否则它有8个邻域。”


这不管用。没有足够的参数。如果你去掉循环,i和j就没有意义了,我知道
i
j
是无用的,应该更改为
row
column
。然后您会得到如下条件:if
row==row-1
。您需要4个参数。两个表示矩阵的尺寸,两个表示单元的坐标。我不是说删除行的
,我只是说设计中不应该有任何循环。我更新了我的答案以澄清。
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