【发布时间】: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是继任者的成本。
这是我迄今为止对实现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
很明显,我没有正确遍历这个元组的元组列表,将它们作为两个添加的元组转移到边缘。
我应该如何遍历这个特定的实现有什么想法吗?
【问题讨论】:
标签: python loops search stack tuples