gpt4 book ai didi

python - python 中的摩尔邻域

转载 作者:太空宇宙 更新时间:2023-11-04 01:12:36 25 4
gpt4 key购买 nike

我有一个网格作为具有整数 (1/0) 的元组的元组,单元格的行号和列号作为整数。而且我必须找出有多少个相邻单元格的邻居是整数。

这是一个来自 www.checkio.org 的任务,这是一个学习 python 的有趣网站。

这是我的代码:

def count_neighbours(grid, row, col):
grid = ()
count = 0
for pos in ((row - 1, col), (row + 1, col), (row, col - 1), (row, col + 1), (row - 1, col - 1), (row - 1, col + 1), (row + 1, col - 1), (row + 1, col + 1)):
if pos == 1:
count += 1
return count

系统回答我所选小区附近没有邻居。请向我解释哪里出了问题,感谢您的关注!

最佳答案

我看到两个明显的错误:

  1. 您用空元组替换了网格

  2. 您的代码根本没有引用 grid 变量,如果 pos 等于,您只需将 count 加 1 1. pos 永远不会等于 1,因为您将其设置为一系列元组中的一个。

因此,只要 rowcol 是数字(并加注否则为异常(exception))。

您需要实际引用传入的网格:

def count_neighbours(grid, row, col):
count = 0
for pos in (
(row - 1, col), (row + 1, col), (row, col - 1),
(row, col + 1), (row - 1, col - 1), (row - 1, col + 1),
(row + 1, col - 1), (row + 1, col + 1)):
if grid[pos[0]][pos[y]] == 1:
count += 1
return count

我在这里假设网格是表示行和单元格的列表列表。

接下来,您必须处理越界的位置;第一行的顶部没有邻居,例如:

def count_neighbours(grid, row, col):
count = 0
for x, y in (
(row - 1, col), (row + 1, col), (row, col - 1),
(row, col + 1), (row - 1, col - 1), (row - 1, col + 1),
(row + 1, col - 1), (row + 1, col + 1)):
if not (0 <= x < len(grid) and 0 <= y < len(grid[x])):
# out of bounds
continue
if grid[x][y] == 1:
count += 1
return count

关于python - python 中的摩尔邻域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26830697/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com