如何从周围的正方形中计算定义的字母的数量?



函数得到一个正方形作为参数,它必须计算它周围有多少个字母N:s。我认为它需要在正确的范围内进行两个for循环但我被如何设置计数字母的界限所困扰。如果给定的正方形在一个字母上,它也被计算在内。

room = [['N', ' ', ' ', ' ', ' '],
['N', 'N', 'N', 'N', ' '],
['N', ' ', 'N', ' ', ' '],
['N', 'N', 'N', ' ', ' '],
[' ', ' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' ', ' ']]  
def count_n(x, y, room):
for y in range(y, len(room)):
#print(y)
for x in range(x, len(room[y])):
#print(x)
if x == "N":
n=n+1
return n

If "表示8个邻居和单元格本身,您可以执行以下操作:

def count_n(x, y, room):
x_lo, x_hi = max(x-1, 0), min(x+2, len(room))
y_lo, y_hi = max(y-1, 0), min(y+2, len(room[x]))
n = 0
for row in room[x_lo:x_hi]:
for val in row[y_lo:y_hi]:
if val == "N":
n = n + 1
return n

可以缩写为:

def count_n(x, y, room):
x_lo, x_hi = max(x-1, 0), min(x+2, len(room))
y_lo, y_hi = max(y-1, 0), min(y+2, len(room[x]))
return sum(val == "N" for row in room[x_lo:x_hi] for val in row[y_lo:y_hi])

相关内容

  • 没有找到相关文章

最新更新