伙计我给了一个任务,我必须找到网格中一个单元格周围的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
答案 0 :(得分:0)
请查看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))