本文整理汇总了Python中util.Stack.push方法的典型用法代码示例。如果您正苦于以下问题:Python Stack.push方法的具体用法?Python Stack.push怎么用?Python Stack.push使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类util.Stack
的用法示例。
在下文中一共展示了Stack.push方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: depthFirstSearch
# 需要导入模块: from util import Stack [as 别名]
# 或者: from util.Stack import push [as 别名]
def depthFirstSearch(problem):
"""
Search the deepest nodes in the search tree first [p 85].
Your search algorithm needs to return a list of actions that reaches
the goal. Make sure to implement a graph search algorithm [Fig. 3.7].
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())
"""
frontier = Stack() # A helper stack of (state,route_to_state)
explored_set = set() # A set of state recording the explored nodes
start = problem.getStartState()
frontier.push((start,list()))
while not frontier.isEmpty():
current_node = frontier.pop()
if problem.isGoalState(current_node[0]): return current_node[1]
successors = problem.getSuccessors(current_node[0])
explored_set.add(current_node[0])
for s in successors:
if s[0] not in explored_set:
current_route = list(current_node[1])
current_route.append(s[1])
frontier.push((s[0],current_route))
print "No route found!"
return list()
示例2: depthFirstSearch
# 需要导入模块: from util import Stack [as 别名]
# 或者: from util.Stack import push [as 别名]
def depthFirstSearch(problem):
"""
Search the deepest nodes in the search tree first
[2nd Edition: p 75, 3rd Edition: p 87]
Your search algorithm needs to return a list of actions that reaches
the goal. Make sure to implement a graph search algorithm
[2nd Edition: Fig. 3.18, 3rd Edition: Fig 3.7].
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()
visited = set()
path = Stack()
start = problem.getStartState()
visited.add(start)
path.push(start)
children = problem.getSuccessors(start)
for child in children:
fringe.push(child)
ds = DFSRec(problem,fringe,visited,path)
if ds != None:
break
pathToGoal = directions(ds)
return pathToGoal
示例3: depthFirstSearch
# 需要导入模块: from util import Stack [as 别名]
# 或者: from util.Stack import push [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()
示例4: depthFirstSearch
# 需要导入模块: from util import Stack [as 别名]
# 或者: from util.Stack import push [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
示例5: depthFirstSearch
# 需要导入模块: from util import Stack [as 别名]
# 或者: from util.Stack import push [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)
示例6: depthFirstSearch
# 需要导入模块: from util import Stack [as 别名]
# 或者: from util.Stack import push [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]])
示例7: depthFirstSearch
# 需要导入模块: from util import Stack [as 别名]
# 或者: from util.Stack import push [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]
示例8: depthFirstSearch
# 需要导入模块: from util import Stack [as 别名]
# 或者: from util.Stack import push [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 []
示例9: depthFirstSearch
# 需要导入模块: from util import Stack [as 别名]
# 或者: from util.Stack import push [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]
示例10: depthFirstSearch
# 需要导入模块: from util import Stack [as 别名]
# 或者: from util.Stack import push [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
#: lista de nodos visitados
closed = []
#: pila que hace la funcion de frontera
frontier = Stack()
# Recogemos el primer estado, creamos un nodo y lo
# insertamos en la pila
frontier.push(Node(problem.getStartState()))
# iteramos hasta que no hayan nodos en la pila
# o hayamos encontrado el objetivo
while not frontier.isEmpty():
#: siguiente nodo a expandir
node = frontier.pop()
# comprobamos si el estado actual nos cumple el objetivo
if problem.isGoalState(node.state):
# si lo cumple, salimos del bucle
break
if node.state not in closed:
# insertamos el estado en la lista de visitados
closed.append(node.state)
# recuperamos los estados sucesores
for successor in problem.getSuccessors(node.state):
frontier.push(Node(
successor[0],
node,
successor[1],
successor[2]))
#: acciones para llegar al objetivo
actions = []
# recorremos mientras haya un action en el nodo previo
while node.action:
actions.append(node.action)
node = node.previous
#mostramos el resultado antes de devolverlo
#print actions[::-1]
return actions[::-1]
示例11: depthFirstSearch
# 需要导入模块: from util import Stack [as 别名]
# 或者: from util.Stack import push [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()
示例12: depthFirstSearch
# 需要导入模块: from util import Stack [as 别名]
# 或者: from util.Stack import push [as 别名]
def depthFirstSearch(problem):
"""
Search the deepest nodes in the search tree first
[2nd Edition: p 75, 3rd Edition: p 87]
Your search algorithm needs to return a list of actions that reaches
the goal. Make sure to implement a graph search algorithm
[2nd Edition: Fig. 3.18, 3rd Edition: Fig 3.7].
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 ***"
print "the problem is ", problem
from game import Directions
s = Directions.SOUTH
w = Directions.WEST
n = Directions.NORTH
e = Directions.EAST
start = problem.getStartState()
if problem.isGoalState(start):
return []
from util import Stack
statesStack = Stack()
exploredSet = set([start])
tup = (start,[])
statesStack.push(tup)
while not statesStack.isEmpty():
tup1 = statesStack.pop()
state = tup1[0]
path = tup1[1]
if problem.isGoalState(state):
return path
successors = problem.getSuccessors(state)
for succ in successors:
coor = succ[0]
move = succ[1]
#cost = succ[2]
tempPath = list(path)
if not coor in exploredSet:
exploredSet.add(coor)
if move == 'North':
tempPath.append(n)
elif move == 'East':
tempPath.append(e)
elif move == 'South':
tempPath.append(s)
elif move == 'West':
tempPath.append(w)
statesStack.push((coor,tempPath))
return []
示例13: depthFirstSearch
# 需要导入模块: from util import Stack [as 别名]
# 或者: from util.Stack import push [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:"""
loc_stack = Stack()
visited_node = {}
parent_child_map = {}
direction_list = []
start_node = problem.getStartState()
parent_child_map[start_node] = []
loc_stack.push(start_node)
def traverse_path(parent_node):
while True:
map_row = parent_child_map[parent_node]
if (len(map_row) == 2):
parent_node = map_row[0]
direction = map_row[1]
direction_list.append(direction)
else:
break
return direction_list
while (loc_stack.isEmpty() == False):
parent_node = loc_stack.pop()
if (problem.isGoalState(parent_node)):
pathlist = traverse_path(parent_node)
pathlist.reverse()
return pathlist
elif (visited_node.has_key(parent_node) == False):
visited_node[parent_node] = []
sucessor_list = problem.getSuccessors(parent_node)
no_of_child = len(sucessor_list)
if (no_of_child > 0):
temp = 0
while (temp < no_of_child):
child_nodes = sucessor_list[temp]
child_state = child_nodes[0];
child_action = child_nodes[1];
if (visited_node.has_key(child_state) == False):
loc_stack.push(child_state)
parent_child_map[child_state] = [parent_node,child_action]
temp = temp + 1
示例14: depthFirstSearch
# 需要导入模块: from util import Stack [as 别名]
# 或者: from util.Stack import push [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
if problem.isGoalState(problem.getStartState()):
return list()
##initialize the list of actions to return, frontier and explored set
frontier = Stack()
listOfActions = list()
##frontier includes the state and the list of actions to get to that state to construct the node
frontier.push( [problem.getStartState(),listOfActions] )
explored = set()
##looping while the frontier is not empty
while not(frontier.isEmpty()):
##pop one node off the frontier, check if it is the goal state
node = frontier.pop()
if problem.isGoalState(node[0]):
return node[1]
##add the state to the explored set if it is not the goal state
explored.add(node[0])
##looping through current state's successor states
for state,action,stepCost in problem.getSuccessors(node[0]):
##add the action needed from current state to next state onto the action list
oldActions = list(node[1])
oldActions.append(action)
nextNode = [state, oldActions]
##push the node onto the frontier if it is unexplored
if(state not in explored):
frontier.push(nextNode)
return None
示例15: depthFirstSearch
# 需要导入模块: from util import Stack [as 别名]
# 或者: from util.Stack import push [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
from game import Directions
s = Directions.SOUTH
w = Directions.WEST
n = Directions.NORTH
e = Directions.EAST
opened = Stack() #create an open stack
start = problem.getStartState()
closed = set([start]) #create a closed list with the root node 1st entry
if problem.isGoalState(start): #failsafe in case root is goal
return []
opened.push((start, []))
while not opened.isEmpty():
tup2 = opened.pop() #remove 1st item from open stack
state = tup2[0]
direction = tup2[1]
if problem.isGoalState(state):
return direction
children = problem.getSuccessors(state) #generate children
for child in children: #name both the coordinates and direction
position = child[0]
direct = child[1]
list_of_paths = list(direction)
if not position in closed: #add to closed list (if not already there)
closed.add(position)
#list_of_paths.append(direction)
if direct == 'North':
list_of_paths.append(n)
elif direct == 'East':
list_of_paths.append(e)
elif direct == 'South':
list_of_paths.append(s)
elif direct == 'West':
list_of_paths.append(w) #keeps track of all directions traveled in dfs
opened.push((position,list_of_paths)) #add children to stack
return []