DFS算法:“list”对象没有“depth”属性

2024-04-29 15:27:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用python来实现DFS搜索算法,但是当我运行代码时,它说“'list'object has no attribute'depth'”,实际上,我代码中的object'node'是class Nodes的一个实例,它将具有我之前确定的属性'depth'。 这是我的密码:

import numpy as np  
class Nodes():   # definite a nodes class. It contains state/parent/depth/action properties 'action' means it is generated by which action, which includes 'UP, DOWN, RIGHT, LEFT'

    def __init__(self, state, parent=None, depth=0, action=None):
        self.state = state
        self.parent = parent
        self.depth = depth
        self.action = action
    #  ....

    def DFS(self, goal, limit):
        opentable = []
        opentable.append(self)
        while True:
            if len(opentable) > 0:
                node = opentable.pop(0)
            if node.depth < limit:   # the problem is here
                if (node.state == goal).all():
                    moves = []
                    temp = node
                    i = 0
                    while True:
                        moves.insert(i, temp.action)
                        if temp.depth == 1:
                            break
                        temp = temp.parent
                        i += 1
                     return moves
                 opentable.append(node.generatenodes())
                 opentable.reverse()


if __name__ == '__main__':
     initial = np.array([[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0],['A', 'B', 'C', 'G']])
     start = Nodes(initial)
     goal = np.array([[0, 0, 0, 0], [0, 'A', 0, 0], [0, 'B', 0, 0],[0, 'C', 0, 'G']])
     start.DFS(goal, 8)

Tags: selfnodeifnpactiontempclassparent