Skip to main content
 首页 » 编程设计

python之如何在 Python 中迭代元组的堆栈

2024年10月24日11lonelyxmas

我正在尝试使用预定义为 Stack 的类在 Python 中实现 DepthFirstSearch 算法:

class Stack: 
    def __init__(self): 
        self.list = [] 
 
    def push(self,item): 
        self.list.append(item) 
 
    def pop(self): 
        return self.list.pop() 
 
    def isEmpty(self): 
        return len(self.list) == 0 

我还有函数:

def isGoalState(self, state): 
    isGoal = state == self.goal 

返回我们是否处于预定义的目标状态, 功能:

def getStartState(self): 
    return self.startState 

返回元组(int,int),代理的位置, 和功能:

def getSuccessors(self, state): 
    self._expanded += 1 
    return successors 

它以 ((int,int),string,int) 的形式返回代理的所有可用下一个“移动”的元组,其中 (int,int) 是后继者的状态,string 是方向(NSEW),int 是后继者的成本。

到目前为止,这是我实现 DepthFirstSearch 的 GraphSearch 的实现:

def depthFirstSearch(problem): 
    closed = [] 
    fringe = util.Stack() 
    fringe.push(problem) 
 
    i = 0 
    while not fringe.isEmpty(): 
        currentState = fringe.pop() 
        print "current's successors:", currentState.getSuccessors(currentState.getStartState()) 
 
        if currentState.isGoalState(currentState.getStartState()): 
            return currentState 
 
        if not (currentState in closed): 
            closed.append(currentState) 
            print "closed now includes:", closed[i].getStartState() 
 
            children = currentState.getSuccessors(currentState.getStartState()) 
            print "children:", children 
 
            while not children.isEmpty(): 
               fringe.push(children.pop()) 
 
            print "fringe:" fringe 
 
        i += 1 

我意识到这还不完整,当我尝试遍历 for x in temp: 中的 temp 时,问题就来了。我通过了第一次迭代,然后第二次停止了。这是终端输出:

current's successors: [((5, 4), 'South', 1), ((4, 5), 'West', 1)] 
closed now includes: (5, 5) 
children: [((5, 4), 'South', 1), ((4, 5), 'West', 1)] 
Traceback (most recent call last): 
... 
... 
... 
AttributeError: 'list' object has no attribute isEmpty 

很明显,我没有正确地遍历这个元组的元组列表,以将它们作为两个添加的元组的元组转移到边缘。

关于我应该如何遍历这个特定实现的任何想法?

请您参考如下方法:

getSuccessors 弹出列表的一个元素并将其返回。列表中的元素本身不是 Stack 的实例,因此它们没有 isEmpty 方法。

请注意,DFS 通常是通过递归实现的;如果这样做,您可能会发现更容易找出哪里出错了。