本文整理汇总了Python中util.Stack.pop方法的典型用法代码示例。如果您正苦于以下问题:Python Stack.pop方法的具体用法?Python Stack.pop怎么用?Python Stack.pop使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类util.Stack
的用法示例。
在下文中一共展示了Stack.pop方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: depthFirstSearch
# 需要导入模块: from util import Stack [as 别名]
# 或者: from util.Stack import pop [as 别名]
def depthFirstSearch(problem):
stack = Stack(); parentNode = []; successors = []; visitedNodes = []
parentChildMapList = {}
stack.push(problem.getStartState())
currentState = problem.getStartState() #need to remove
while problem.isGoalState(currentState) is False and problem.isGoalState(currentState[0]) is False:
if(currentState == problem.getStartState()):
successors = problem.getSuccessors(currentState)
visitedNodes.append(currentState)
else:
successors = problem.getSuccessors(currentState[0])
visitedNodes.append(currentState[0])
if successors != None and len(successors) > 0 :
parentNode.append(currentState)
for node in successors:
if(visitedNodes.__contains__(node) == False and visitedNodes.__contains__(node[0]) == False):
stack.push(node)
parentChildMapList[node] = currentState
tempCurrentNode = stack.pop()
if(visitedNodes.__contains__(tempCurrentNode) == False and visitedNodes.__contains__(tempCurrentNode[0]) == False):
currentState = tempCurrentNode
else:
currentState = stack.pop()
validDirections = []
firstState = currentState
while firstState != problem.getStartState():
validDirections.append(firstState[1])
firstState = parentChildMapList[firstState]
validDirections.reverse()
return validDirections
util.raiseNotDefined()
示例2: depthFirstSearch
# 需要导入模块: from util import Stack [as 别名]
# 或者: from util.Stack import pop [as 别名]
def depthFirstSearch(problem):
successor_idx = {'dir': 1, 'state': 0, 'cost': -1}
MAX_ITER = int(20000)
stateStack = Stack()
visitedSet = set()
actionList = [] # add actions to get to the state, use pop to remove last one
successorDict = {}
curState = problem.getStartState()
stateStack.push(curState)
for it in range(MAX_ITER):
if problem.isGoalState(curState):
return actionList
if curState not in visitedSet:
successors = problem.getSuccessors(curState)
successorDict[curState] = successors
visitedSet.add(curState)
nStateTuple = filter(lambda x: x[0] not in visitedSet, successorDict[curState]) # get next state
if len(nStateTuple) == 0:
stateStack.pop()
actionList.pop()
curState = stateStack.list[-1]
else:
curState = nStateTuple[0][successor_idx['state']]
stateStack.push(curState)
actionList.append(nStateTuple[0][successor_idx['dir']])
return []
示例3: depthFirstSearch
# 需要导入模块: from util import Stack [as 别名]
# 或者: from util.Stack import pop [as 别名]
def depthFirstSearch(problem):
"""
Search the deepest nodes in the search tree first.
Your search algorithm needs to return a list of actions that reaches the
goal. Make sure to implement a graph search algorithm.
To get started, you might want to try some of these simple commands to
understand the search problem that is being passed in:
print "Start:", problem.getStartState()
print "Is the start a goal?", problem.isGoalState(problem.getStartState())
print "Start's successors:", problem.getSuccessors(problem.getStartState())
"""
"*** YOUR CODE HERE ***"
from util import Stack
fringe = Stack() # Fringe to manage which states to expand
fringe.push(problem.getStartState())
visited = [] # List to check whether state has already been visited
path=[] # Final direction list
pathToCurrent=Stack() # Stack to maintaing path from start to a state
currState = fringe.pop()
while not problem.isGoalState(currState):
if currState not in visited:
visited.append(currState)
successors = problem.getSuccessors(currState)
for child,direction,cost in successors:
fringe.push(child)
tempPath = path + [direction]
pathToCurrent.push(tempPath)
currState = fringe.pop()
path = pathToCurrent.pop()
return path
示例4: __init__
# 需要导入模块: from util import Stack [as 别名]
# 或者: from util.Stack import pop [as 别名]
class QueueTheStack:
"A container with a first-in-first-out (FIFO) queuing policy."
def __init__(self):
self.Stack1 = Stack()
self.Stack2 = Stack()
"add adequate number of stacks here"
"*** WRITE CODE HERE ***"
def push(self,item):
self.Stack1.push(item);
"Enqueue the 'item' into the queue"
"*** WRITE CODE HERE ***"
def pop(self):
while (not self.Stack1.isEmpty()):
self.Stack2.push(self.Stack1.pop())
toreturn = self.Stack2.pop()
while (not self.Stack2.isEmpty()):
self.Stack1.push(self.Stack2.pop())
return toreturn
"dequeue the 'item' from the queue"
"*** WRITE CODE HERE ***"
def isEmpty(self):
return self.Stack1.isEmpty()
"returns true if the queue is empty"
"***WRITE CODE HERE***"
示例5: postorder_traverse_3
# 需要导入模块: from util import Stack [as 别名]
# 或者: from util.Stack import pop [as 别名]
def postorder_traverse_3(root):
"""postorder_traverse_3
algorithm:
push/pop node to stack according to current node's state
"""
ns = [root, VISIT_LEFT] #(node, state)
stack = Stack([], debug=True)
while ns or stack:
while ns:
stack.append(ns)
node, state = ns
#ns[1] == VISIT_LEFT
ns[1] = VISIT_RIGHT
if node.left:
ns = [node.left, VISIT_LEFT]
else:
ns = None
ns = stack[-1]
if ns[1] == VISIT_RIGHT:
ns[1] = VISIT_SELF
if ns[0].right:
ns = [ns[0].right, VISIT_LEFT]
else:
ns = None
elif ns[1] == VISIT_SELF:
yield ns[0]
stack.pop()
ns = None
示例6: find_immediate_common_ancestor_2
# 需要导入模块: from util import Stack [as 别名]
# 或者: from util.Stack import pop [as 别名]
def find_immediate_common_ancestor_2(root, value1, value2):
"""find_immediate_common_ancestor_2
algorithm:
in post-order, the stack holds all the parent node
when find the first value, the parent list only shrink on the
road to find the 2nd value.
"""
p, last_visited, immediate_ancestor = root, None, None
#stack = Stack([], debug=True)
stack = Stack([])
while p or stack:
while p:
stack.append(p)
p = p.left
p = stack[-1]
if not p.right or p.right == last_visited:
stack.pop()
#^#
if p.value in (value1, value2):
if not immediate_ancestor:
immediate_ancestor = stack[-1]
else:
return immediate_ancestor.value
if p == immediate_ancestor:
if stack:
immediate_ancestor = stack[-1]
#$#
last_visited = p
p = None
else:
p = p.right
示例7: depthFirstSearch
# 需要导入模块: from util import Stack [as 别名]
# 或者: from util.Stack import pop [as 别名]
def depthFirstSearch(problem):
"""
Search the deepest nodes in the search tree first.
Your search algorithm needs to return a list of actions that reaches the
goal. Make sure to implement a graph search algorithm.
To get started, you might want to try some of these simple commands to
understand the search problem that is being passed in:
print "Start:", problem.getStartState()
print "Is the start a goal?", problem.isGoalState(problem.getStartState())
print "Start's successors:", problem.getSuccessors(problem.getStartState())
"""
#Init variables
currentCoordinate = problem.getStartState() #The current coordinate we are evaluating
pathToCurrentCoordinate = [] #The current list we are using and updating
fringeCoordinateList = Stack() #List of current edge coordinates, can have duplications
fringeCoordinateList.push(currentCoordinate)
previouslyVisitedCoordinatesList = [] #List of previously visited coordinates
pathsToCoordinates = Stack() #List of lists of actions
pathsToCoordinates.push(pathToCurrentCoordinate)
#First run through
while(not problem.isGoalState(currentCoordinate) and not fringeCoordinateList.isEmpty()):
#Find the next coordinate from the fringe, that we haven't visited before
topFringeCoordinate = fringeCoordinateList.pop()
pathToCurrentCoordinate = pathsToCoordinates.pop()
while(topFringeCoordinate in previouslyVisitedCoordinatesList):
topFringeCoordinate = fringeCoordinateList.pop()
pathToCurrentCoordinate = pathsToCoordinates.pop()
currentCoordinate = topFringeCoordinate
#Hotfix for autograder
if (problem.isGoalState(currentCoordinate)):
break;
#Add new fringe coordinates to the list, and update the action lists as appropriate
successors = problem.getSuccessors(currentCoordinate)
for successor in successors:
fringeCoordinateList.push(successor[0])
newActionList = list(pathToCurrentCoordinate) #Copy list
newActionList.append(successor)
pathsToCoordinates.push(newActionList)
#Mark that we have visited the current coordinate
previouslyVisitedCoordinatesList.append(currentCoordinate)
result = []
for action in pathToCurrentCoordinate:
result.append(action[1])
return result
示例8: depthFirstSearch
# 需要导入模块: from util import Stack [as 别名]
# 或者: from util.Stack import pop [as 别名]
def depthFirstSearch(problem):
from collections import defaultdict
from util import Stack
initial_node=problem.getStartState()
current_node=defaultdict(list)
current_node[initial_node].append("No parent")
current_node[initial_node].append("No direction")
stack=Stack()
stack.push(current_node)
current_node=stack.pop()
direction_list={}
Child=current_node.keys()
Parent=current_node.values()[0]
visited_list={}
while (problem.isGoalState(Child[0]) is not True):
if(Child[0] in visited_list.keys()):
current_node=stack.pop()
Child=current_node.keys()
Parent=current_node.values()[0]
else:
visited_list[Child[0]]=Parent[0]
direction_list[Child[0]]=Parent[1]
Successor_node=problem.getSuccessors(Child[0])
for index in range(len(Successor_node)):
temp_dict=defaultdict(list)
temp_dict[Successor_node[index][0]].append(Child[0])
temp_dict[Successor_node[index][0]].append(Successor_node[index][1])
#print"The temp dict values are",temp_dict
stack.push(temp_dict)
#print " The heap of queue is",priority_queue.heap
current_node=stack.pop()
#print "The current node is",current_node
Child=current_node.keys()
Parent=current_node.values()[0]
visited_list[Child[0]]= Parent[0]
direction_list[Child[0]]=Parent[1]
backtracking =[]
path = Child[0]
backtracking.append(direction_list[path])
path = visited_list[path]
print "The path is",path
while (path!= problem.getStartState()):
backtracking.append(direction_list[path])
path = visited_list[path]
backtracking.reverse()
return backtracking
util.raiseNotDefined()
示例9: find_immediate_common_ancestor_5
# 需要导入模块: from util import Stack [as 别名]
# 或者: from util.Stack import pop [as 别名]
def find_immediate_common_ancestor_5(root, value1, value2):
"""find_immediate_common_ancestor_5
algorithm:
pre-order traversal with value for each level
"""
if not root:
return
ancestor, immediate_ancestor_level = {}, -1
stack = Stack([(root, 0)])
while stack:
p, level = stack.pop()
#^#
ancestor[level] = p
if p.value in (value1, value2):
if immediate_ancestor_level == -1:
immediate_ancestor_level = level - 1
else:
return ancestor[immediate_ancestor_level].value
if immediate_ancestor_level > level - 1:
immediate_ancestor_level = level - 1
#$#
if p.right:
stack.append((p.right, level+1))
if p.left:
stack.append((p.left, level+1))
示例10: depthFirstSearch
# 需要导入模块: from util import Stack [as 别名]
# 或者: from util.Stack import pop [as 别名]
def depthFirstSearch(problem):
"""
Search the deepest nodes in the search tree first
Your search algorithm needs to return a list of actions that reaches
the goal. Make sure to implement a graph search algorithm
To get started, you might want to try some of these simple commands to
understand the search problem that is being passed in:
print "Start:", problem.getStartState()
print "Is the start a goal?", problem.isGoalState(problem.getStartState())
print "Start's successors:", problem.getSuccessors(problem.getStartState())
"""
"*** YOUR CODE HERE ***"
'''util.raiseNotDefined()'''
from util import Stack
path=[]
closedList=[]
cost=0
fringe = Stack()
node=[path, cost ,problem.getStartState()]
fringe.push(node)
while (1):
if fringe.isEmpty():
raise Exception, 'no solutiion'
newState=fringe.pop()
if problem.isGoalState(newState[2]):
return newState[0]
if newState[2] not in closedList:
closedList.append(newState[2])
for x in problem.getSuccessors(newState[2]):
fringe.push([newState[0]+[str(x[1])],newState[1]+x[2],x[0]])
示例11: depthFirstSearch
# 需要导入模块: from util import Stack [as 别名]
# 或者: from util.Stack import pop [as 别名]
def depthFirstSearch(problem):
"""
Search the deepest nodes in the search tree first.
Your search algorithm needs to return a list of actions that reaches the
goal. Make sure to implement a graph search algorithm.
To get started, you might want to try some of these simple commands to
understand the search problem that is being passed in:
print "Start:", problem.getStartState()
print "Is the start a goal?", problem.isGoalState(problem.getStartState())
print "Start's successors:", problem.getSuccessors(problem.getStartState())
"""
"*** YOUR CODE HERE ***"
from util import Stack
frontier=Stack()
start_node = Node(problem.getStartState(), step_cost=0)
explored = []
frontier.push(start_node)
while not frontier.isEmpty():
node = frontier.pop()
explored.append(node.state)
if problem.isGoalState(node.state):
return node.getPath()
for child in node.getChildren(problem):
if not child.state in explored:
frontier.push(child)
示例12: postorder_traverse_4
# 需要导入模块: from util import Stack [as 别名]
# 或者: from util.Stack import pop [as 别名]
def postorder_traverse_4(root):
"""postorder_traverse_4
algorithm:
improve postorder_traverse_3 based on the fact that if last visited
node is current node's right child, then current node should be popped up
"""
stack = Stack([], debug=True)
node = root
last_visited = None
while True:
# push
while node:
stack.append(node)
node = node.left
if not stack: break
# top/pop
node = stack[-1]
if not node.right or node.right == last_visited:
node = stack.pop()
yield node
last_visited = node
# prepare next
node = None
else:
# prepare next
node = node.right
示例13: depthFirstSearch
# 需要导入模块: from util import Stack [as 别名]
# 或者: from util.Stack import pop [as 别名]
def depthFirstSearch(problem):
"Search the shallowest nodes in the search tree first. [p 81]"
from util import Stack
BFS1 = Stack()
Moves = []
Visited = []
Final = []
NewState = (0, (problem.getStartState(), 'Start', 0))
#print CurrentState
BFS1.push([NewState])
while not BFS1.isEmpty():
NewState = BFS1.pop()
if problem.isGoalState(NewState[0][1][0]):
Final = NewState
break
if Visited.count(NewState[0][1][0]) == 0:
#print NewState
for item in enumerate(problem.getSuccessors(NewState[0][1][0])):
#print item
BFS1.push([item] + NewState)
Visited.append(NewState[0][1][0])
for nodes in Final:
Moves.append(nodes[1][1])
Moves.reverse()
Moves.remove('Start')
#print Moves
return Moves
示例14: depthFirstSearch
# 需要导入模块: from util import Stack [as 别名]
# 或者: from util.Stack import pop [as 别名]
def depthFirstSearch(problem):
"""
Search the deepest nodes in the search tree first.
Your search algorithm needs to return a list of actions that reaches the
goal. Make sure to implement a graph search algorithm.
To get started, you might want to try some of these simple commands to
understand the search problem that is being passed in:
print "Start:", problem.getStartState()
print "Is the start a goal?", problem.isGoalState(problem.getStartState())
print "Start's successors:", problem.getSuccessors(problem.getStartState())
"""
from util import Stack
start = problem.getStartState()
checkStack = Stack()
checkStack.push((start,[]))
visitedStates = []
while not checkStack.isEmpty():
popState, popDirection = checkStack.pop()
for successors in problem.getSuccessors(popState):
state, direction, cost = successors
if not state in visitedStates:
if problem.isGoalState(state):
print state
return popDirection + [direction]
checkStack.push((state,popDirection+[direction]))
visitedStates = visitedStates+[popState]
示例15: depthFirstSearch
# 需要导入模块: from util import Stack [as 别名]
# 或者: from util.Stack import pop [as 别名]
def depthFirstSearch(problem):
"""
Search the deepest nodes in the search tree first.
Your search algorithm needs to return a list of actions that reaches the
goal. Make sure to implement a graph search algorithm.
To get started, you might want to try some of these simple commands to
understand the search problem that is being passed in:
print "Start:", problem.getStartState()
print "Is the start a goal?", problem.isGoalState(problem.getStartState())
print "Start's successors:", problem.getSuccessors(problem.getStartState())
"""
"*** YOUR CODE HERE ***"
stateStack = Stack()
state = problem.getStartState()
state = [(state, "Stop", 0)]
stateStack.push(state)
while not problem.isGoalState(state[len(state) - 1][0]):
state = stateStack.pop()
successors = problem.getSuccessors(state[len(state) - 1][0])
for successor in successors:
if successor[0] not in [position[0] for position in state]:
stateStack.push(state + [successor])
return [direction[1] for direction in state]