AI搜索程序不输出搜索矩阵

我编写并运行了一个AI搜索程序,从起点开始搜索直到找到终点或结果。然而,当我运行它时,我没有得到搜索结果,反而得到了“fail”和“none”。任何关于可能导致此问题的原因的建议将不胜感激。


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 = 1delta = [[-1, 0], # go up         [ 0,-1], # go left         [ 1, 0], # go down         [ 0, 1]] # go rightdelta_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] = 1print search()


回答:

第一个问题出现在代码的这一部分:

x = next[3]y = next[4]g = next[1]

open列表中的每个元素只有三个条目,因此34是无效的索引。这应该改为:

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

x2y2都与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

或者使用xy这样的变量名来表示坐标可能会引起混淆。从技术上讲这不是问题,但在这种实现中,x坐标会被带有“向上”和“向下”注释的条目修改,而y坐标会被“向左”和“向右”修改。

Related Posts

L1-L2正则化的不同系数

我想对网络的权重同时应用L1和L2正则化。然而,我找不…

使用scikit-learn的无监督方法将列表分类成不同组别,有没有办法?

我有一系列实例,每个实例都有一份列表,代表它所遵循的不…

f1_score metric in lightgbm

我想使用自定义指标f1_score来训练一个lgb模型…

通过相关系数矩阵进行特征选择

我在测试不同的算法时,如逻辑回归、高斯朴素贝叶斯、随机…

可以将机器学习库用于流式输入和输出吗?

已关闭。此问题需要更加聚焦。目前不接受回答。 想要改进…

在TensorFlow中,queue.dequeue_up_to()方法的用途是什么?

我对这个方法感到非常困惑,特别是当我发现这个令人费解的…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注