如何在Python中迭代一堆元组元组

时间:2016-02-14 10:53:34

标签: python loops search stack tuples

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

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是继任者的代价。

以下是我实施GraphSearch实施DepthFirstSearch时的情况:

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

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

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

1 个答案:

答案 0 :(得分:2)

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

请注意,DFS通常通过递归实现;如果你这样做,你可能会发现更容易找到出错的地方。