当前位置: 首页>>代码示例>>Python>>正文


Python Stack.isEmpty方法代码示例

本文整理汇总了Python中util.Stack.isEmpty方法的典型用法代码示例。如果您正苦于以下问题:Python Stack.isEmpty方法的具体用法?Python Stack.isEmpty怎么用?Python Stack.isEmpty使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在util.Stack的用法示例。


在下文中一共展示了Stack.isEmpty方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: __init__

# 需要导入模块: from util import Stack [as 别名]
# 或者: from util.Stack import isEmpty [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***"
开发者ID:ahmerlums,项目名称:CS331-Artificial-Intelligence,代码行数:34,代码来源:QueueTheStack.py

示例2: depthFirstSearch

# 需要导入模块: from util import Stack [as 别名]
# 或者: from util.Stack import isEmpty [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
开发者ID:prasidh09,项目名称:Pacman_Projects,代码行数:29,代码来源:search.py

示例3: depthFirstSearch

# 需要导入模块: from util import Stack [as 别名]
# 或者: from util.Stack import isEmpty [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]])
开发者ID:danielzhangyihao,项目名称:myProjects,代码行数:35,代码来源:search.py

示例4: depthFirstSearch

# 需要导入模块: from util import Stack [as 别名]
# 或者: from util.Stack import isEmpty [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)
开发者ID:bottleling,项目名称:pacmansearch,代码行数:30,代码来源:search.py

示例5: depthFirstSearch

# 需要导入模块: from util import Stack [as 别名]
# 或者: from util.Stack import isEmpty [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]
开发者ID:sindhuula,项目名称:Sem2,代码行数:31,代码来源:search.py

示例6: depthFirstSearch

# 需要导入模块: from util import Stack [as 别名]
# 或者: from util.Stack import isEmpty [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()
开发者ID:luowei89,项目名称:neu-courses,代码行数:35,代码来源:search.py

示例7: depthFirstSearch

# 需要导入模块: from util import Stack [as 别名]
# 或者: from util.Stack import isEmpty [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
开发者ID:robertsmieja,项目名称:CS4341-AI,代码行数:59,代码来源:search.py

示例8: depthFirstSearch

# 需要导入模块: from util import Stack [as 别名]
# 或者: from util.Stack import isEmpty [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]
开发者ID:hermetico,项目名称:IA,代码行数:58,代码来源:search.py

示例9: hanoi

# 需要导入模块: from util import Stack [as 别名]
# 或者: from util.Stack import isEmpty [as 别名]
def hanoi (n, source, helper, target):
	
	
	if n==1:
		target.push(source.pop())
	else:

		hanoi(n-1,source,target,helper)
		target.push(source.pop())
		hanoi(n-1,helper,source,target)

	print "source " 
	print
	temp = Stack()
	while not source.isEmpty():
		t = source.pop()
		temp.push(t)
		print t
	while not temp.isEmpty():
		t = temp.pop()
		source.push(t)
	print "helper " 
	print
	temp = Stack()
	while not helper.isEmpty():
		t = helper.pop()
		temp.push(t)
		print t
	while not temp.isEmpty():
		t = temp.pop()
		helper.push(t)
	print "target"
	print
	temp = Stack()
	while not target.isEmpty():
		t = target.pop()
		temp.push(t)
		print t
	while not temp.isEmpty():
		t = temp.pop()
		target.push(t)
	print 
	print
开发者ID:ahmerlums,项目名称:CS331-Artificial-Intelligence,代码行数:45,代码来源:hanoi.py

示例10: depthFirstSearch

# 需要导入模块: from util import Stack [as 别名]
# 或者: from util.Stack import isEmpty [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 []
开发者ID:Nirvana-icy,项目名称:pacman,代码行数:57,代码来源:search.py

示例11: depthFirstSearch

# 需要导入模块: from util import Stack [as 别名]
# 或者: from util.Stack import isEmpty [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
开发者ID:terry2012,项目名称:AI-PacMan-Projects,代码行数:55,代码来源:search.py

示例12: depthFirstSearch

# 需要导入模块: from util import Stack [as 别名]
# 或者: from util.Stack import isEmpty [as 别名]
def depthFirstSearch(problem):
    from game import Directions
    from util import Stack

    South = Directions.SOUTH
    West = Directions.WEST
    East = Directions.EAST
    North = Directions.NORTH
    stop = Directions.STOP

    """
    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())
    """

    ans = []
    ParentNode = {}
    direction = {}
    stack = Stack()
    startNode = problem.getStartState()
    visitedList = []
    stack.push(startNode)
    if problem.isGoalState(startNode):
        return stop

    while stack.isEmpty() == False:
        currentNode = stack.pop()
        visitedList.append(currentNode)
        if problem.isGoalState(currentNode):
            goalPath = currentNode
            while goalPath != startNode:
                ans.append(direction[goalPath])
                goalPath = ParentNode[goalPath]
            return ans[::-1]
        allCurrentSuccessor = problem.getSuccessors(currentNode)
        for Node in allCurrentSuccessor:
            if not Node[0] in visitedList:
                stack.push(Node[0])
                ParentNode[Node[0]] = currentNode
                direction[Node[0]] = Node[1]

    return stop
    util.raiseNotDefined()
开发者ID:acrobat3,项目名称:search_problem,代码行数:54,代码来源:search.py

示例13: depthFirstSearch

# 需要导入模块: from util import Stack [as 别名]
# 或者: from util.Stack import isEmpty [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
开发者ID:kli66,项目名称:UWMadison,代码行数:54,代码来源:search.py

示例14: depthFirstSearch

# 需要导入模块: from util import Stack [as 别名]
# 或者: from util.Stack import isEmpty [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 []
开发者ID:Christine-Mossiah,项目名称:Pacman_search,代码行数:54,代码来源:search.py

示例15: depthFirstSearch

# 需要导入模块: from util import Stack [as 别名]
# 或者: from util.Stack import isEmpty [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:
  """
  from game import Directions
  s = Directions.SOUTH
  w = Directions.WEST
  n = Directions.NORTH
  e = Directions.EAST
  
  visitedlist = []
  st = Stack()
  outputlist = []
  st.push(problem.getStartState())
  visitedlist.append(problem.getStartState())
  recurseDFS(st,problem,visitedlist)
  if st.isEmpty():
    print "No Path exist"
  else:
    while not st.isEmpty():
      value = st.pop()
      if len(value) == 2:
        continue
      if value[1] == 'South':
        outputlist.append(s)
      elif value[1] == 'North':
        outputlist.append(n)
      elif value[1] == 'East':
        outputlist.append(e)
      elif value[1] == 'West':
        outputlist.append(w)
      
  return outputlist[::-1]
开发者ID:Dexhub,项目名称:CSE-537-AI,代码行数:41,代码来源:search.py


注:本文中的util.Stack.isEmpty方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。