【问题标题】:How to Iterate through a Stack of a Tuple of Tuples in Python如何在 Python 中遍历一组元组的元组
【发布时间】:2016-05-25 06:34:34
【问题描述】:

我正在尝试使用预定义为的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是继任者的成本。

这是我迄今为止对实现GraphSearchDepthFirstSearch 的实现:

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

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

我应该如何遍历这个特定的实现有什么想法吗?

【问题讨论】:

    标签: python loops search stack tuples


    【解决方案1】:

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

    请注意,DFS 通常是通过递归实现的;如果这样做,您可能会发现更容易找出问题所在。

    【讨论】:

    • 我应该如何处理这些信息?我正在使用的算法骨架不包括递归,因为它的图形化而不能
    • 我现在明白你的意思了。感谢您的帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-22
    • 2019-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多