【问题标题】:moore neighbourhood code to find number of neighbour cells with 1s摩尔邻域代码查找具有 1 的相邻单元格的数量
【发布时间】:2016-05-21 05:54:45
【问题描述】:

我给了一个任务,我必须在网格中找到一个单元格周围的 1 的数量。example 从示例图中我应该得到 3,因为单元格周围有 3 个 1。所以我做了代码,我做对了,但是当我使用一个函数来做同样的代码时,它给了我错误,我需要你的帮助。

def count_neighbours(((1, 0, 0, 1, 0),(0, 1, 0, 0, 0),(0, 0, 1, 0, 1),(1, 0, 0, 0, 0),(0, 0, 1, 0, 0),), 1, 2):
grid=count_neighbours[0]
row=count_neighbours[1]
col=count_neighbours[2]
length=len(grid)
s=0
d=0
for i in range(row-1,row+2):
    for j in range(col-1,col+2):
        if i>=0 and j>=0:
            if i<=length-1 and j<=length-1:
                if grid[i][j]==1:
                    s+=1
if grid[row][col]==1:
    d+=1
total = s-d
return total
#error goes like this
def count_neighbours(((1, 0, 0, 1, 0),(0, 1, 0, 0, 0),(0, 0, 1, 0, 1),(1, 0, 0, 0, 0),(0, 0, 1, 0, 0),), 1, 2):
                     ^
SyntaxError: invalid syntax

【问题讨论】:

    标签: function python-3.x neighbours


    【解决方案1】:

    请查看python中函数定义的基础知识。不应将输入值放在函数定义中。

    我觉得这就是你要找的。

    def count_neighbours(inputgrid):
        grid=inputgrid[0]
        row=inputgrid[1]
        col=inputgrid[2]
        length=len(grid)
        s=0
        d=0
        for i in range(row-1,row+2):
            for j in range(col-1,col+2):
                if i>=0 and j>=0:
                    if i<=length-1 and j<=length-1:
                        if grid[i][j]==1:
                            s+=1
        if grid[row][col]==1:
            d+=1
        total = s-d
        print (total)
        return total
    
    
    count_neighbours((((1, 0, 0, 1, 0),(0, 1, 0, 0, 0),(0, 0, 1, 0, 1),(1, 0, 0, 0, 0),(0, 0, 1, 0, 0),), 1, 2))
    

    【讨论】:

      猜你喜欢
      • 2023-03-26
      • 2021-07-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多