python - AI 搜索程序不输出搜索矩阵
问题描述
编写并运行了一个 AI 搜索程序,从头到尾运行搜索或找到结果。但是,当我运行它时,我没有得到搜索结果,而是失败并且没有。任何想法可能是问题的原因将不胜感激
grid = [[0, 0, 1, 0, 0, 0],
[0, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 1, 0],
[0, 0, 1, 1, 1, 0],
[0, 0, 0, 0, 1, 0]]
init = [0, 0]
goal = [len(grid)-1, len(grid[0])-1]
cost = 1
delta = [[-1, 0], # go up
[ 0,-1], # go left
[ 1, 0], # go down
[ 0, 1]] # go right
delta_name = ['^', '<', 'v', '>']
def search():
closed = [[0 for row in range(len(grid[0]))] for col in range(len(grid))]
closed[init[0]][init[1]] = 1
x = init[0]
y =init[1]
g = 0
open = [[g, x, y]]
found = False
resign = False
while found is False and resign is False:
if len(open) == 0:
resign = True
print 'fail'
else:
open.sort()
open.reverse()
next = open.pop()
x = next[3]
y = next[4]
g = next[1]
if x == goal[0] and y == goal[1]:
found = next
print next
else:
for i in range(len(delta)):
x2 = x + delta[i][0]
y2 = y + delta[i][1]
if x2 >= 0 and x2 < len(grid) and y2 >= 0 and y2 < len(grid):
if closed[x2][y2] == 0 and grid[x2][y2] == 0:
g2 = g + cost
open.append([g2, x2, y2])
closed[x2][y2] = 1
print search()
解决方案
第一个问题出在这部分代码中:
x = next[3]
y = next[4]
g = next[1]
列表中的每个元素open
只有三个条目,因此3
和4
是无效索引。这可能应该更改为:
x = next[1]
y = next[2]
g = next[0]
第二个问题在这部分的第一行:
if x2 >= 0 and x2 < len(grid) and y2 >= 0 and y2 < len(grid):
if closed[x2][y2] == 0 and grid[x2][y2] == 0:
g2 = g + cost
两者x2
和y2
都与 进行比较len(grid)
,但您似乎没有方形网格,因此其中一项检查将不正确。大概应该改成:
if x2 >= 0 and x2 < len(grid) and y2 >= 0 and y2 < len(grid[0]):
if closed[x2][y2] == 0 and grid[x2][y2] == 0:
g2 = g + cost
潜在的第三个问题是函数的意图似乎是search()
返回一些东西,但它没有任何return
声明。然后它会自动总是返回None
,这意味着print search()
底部的语句总是简单地打印None
。从您的问题中不清楚您希望函数返回什么,所以我无法确定如何修复它。
观察这部分中的任何一个评论都令人困惑也可能很有用:
delta = [[-1, 0], # go up
[ 0,-1], # go left
[ 1, 0], # go down
[ 0, 1]] # go right
或者使用变量名称(例如x
和y
表示坐标)令人困惑。在技术意义上不是问题,但在此实现中,x
坐标由带有“上”和“下”注释的条目修改,而y
坐标由“左转”和“右转”修改。
推荐阅读
- javascript - 为什么事件侦听器中的“this”是窗口而不是元素?
- c++ - clang 格式可以格式化 C/C++ 函数以在逗号之前破坏参数列表吗?
- node.js - node.js/express.js 应用程序中相同组件的问题
- java - Java中的compare()和compareUnsigned()有什么区别
- qt - 如何获取组合框的选定项目并将其保存为 intiger
- objective-c - 当使用 gcc 运行objective-c | AppleEvents.h 错误
- android - 带有描述和预览图像的自定义 TitleView Android TV (FireTV)
- c++ - 为什么使用 cmake 进行安装后包含文件夹为空?
- cuda - 如何在推力集操作中动态设置 device_vectors 的大小?
- python - 为什么python删除影响类实例的函数