Esempio n. 1
0
def dfs(problem):
    """
    Depth first graph search algorithm - implemented for you
    returns a solution for the given search problem
    :param
    problem (a Problem object) representing the quest
            see Problem class definition in spartanquest.py)
    :return: list of actions representing the solution to the quest
                or None if there is no solution
    """
    closed = set()  # keep track of our explored states
    fringe = data_structures.Stack()  # for dfs, the fringe is a stack
    state = problem.start_state()
    root = data_structures.Node(state)
    fringe.push(root)
    while True:
        if fringe.is_empty():
            return None  # Failure - fringe is empty and no solution was found
        node = fringe.pop()
        if problem.is_goal(node.state):
            return node.solution()
        if node.state not in closed:  # we are implementing graph search
            closed.add(node.state)
            for child_state, action, action_cost in problem.successors(
                    node.state):
                child_node = data_structures.Node(child_state, node, action)
                fringe.push(child_node)
 def test_pop_empty(self):
     test_stack = data_structures.Stack()
     try:
         popped = test_stack.pop()
     except:
         pass
     else:
         assert False, "Expected an exception; instead got a Node with value '{}'.".format(
             popped.data)
 def test_stack(self):
     x = data_structures.Stack()
     x.push('lorem')
     x.push('dim')
     x.push('sum')
     x.push('Cha')
     x.push('siu')
     x.push('bao')
     return x
Esempio n. 4
0
import data_structures as ds

#==================================
#           STACK TESTS
#==================================

# test initialisation conditions
stack = ds.Stack()
assert stack.size() == 0
assert stack.isEmpty()

# test push() conditions
stack.push('abc')
assert stack.size() == 1
assert not stack.isEmpty()

# test pop() conditions
assert stack.pop() == 'abc'
assert stack.size() == 0
assert stack.isEmpty()

# test null cases
assert stack.pop() == None
assert stack.peek() == None

# test correct execution
stackwithwrapper = ds.Stack([0, 1, 2, 3], )
assert stackwithwrapper.pop() == 3
assert stackwithwrapper.peek() == 2
assert stackwithwrapper.size() == 3