Ejemplo n.º 1
0
 def runTest(self):
     print "Path result for DFS:", search.depthFirstSearch(self)
     print "Path result for BFS:", search.breadthFirstSearch(self)
     print "Path result for UCS:", search.uniformCostSearch(self)
     print "Path result for A*:", search.aStarSearch(
         self, search.nullHeuristic)
     print "Path result for A* with letter heuristic:", search.aStarSearch(
         self, letterHeuristic)
Ejemplo n.º 2
0
    def solve(self):
        """Solve the current 8-puzzle using the selected algorithm.

        """
        self.clearStats()

        self.problem = eightPuzzle.EightPuzzleSearchProblem(self.puzzle)
        searchAlgorithm = self.algorithm.get()
        if searchAlgorithm == "Depth-first Search":
            self.solution = search.depthFirstSearch(self.problem)
            self.stateHistory = self.solution[3]
        elif searchAlgorithm == "Breadth-first Search":
            self.solution = search.breadthFirstSearch(self.problem)
            self.stateHistory = self.solution[3]
            pass
        elif searchAlgorithm == "Uniform-cost Search":
            self.solution = search.uniformCostSearch(self.problem)
            self.stateHistory = self.solution[3]
            pass
        elif searchAlgorithm == "Greedy Best-first Search":
            #self.solution = search.greedyBestFirstSearch(self.problem)
            #self.stateHistory = self.solution[3]
            pass
        elif searchAlgorithm == "A* Search [Manhattan Dist.]":
            #self.solution = search.aStarSearch(self.problem)
            #self.stateHistory = self.solution[3]
            pass
        else:
            #self.solution = search.recursiveBestFirstSearch(self.problem)
            #self.stateHistory = self.solution[3]
            pass

        self.stats = tk.Label(self, text= (
                "A solution was found in %.3f seconds and requires %s moves."
                %(
                    self.solution[2],
                    (len(self.solution[0]) - 1)
                    )
                )
            )
        self.stats.grid(row=3, column=1, columnspan=5)

        self.stats2 = tk.Label(self, text= (
                "%s nodes were expanded during the search."
                %(len(self.solution[1]))
                )
            )
        self.stats2.grid(row=4, column=1, columnspan=5)

        self.stepInfo = tk.Label(self, text= (
            "Use Previous and Next to show the solution moves.")
            )
        self.stepInfo.grid(row=5, column=1, columnspan=5, padx=5, pady=5)
Ejemplo n.º 3
0
    def findPathToClosestDot(self, gameState):
        "Returns a path (a list of actions) to the closest dot, starting from gameState"
        # Here are some useful elements of the startState
        startPosition = gameState.getPacmanPosition()
        food = gameState.getFood()
        walls = gameState.getWalls()
        problem = AnyFoodSearchProblem(gameState)

        "*** YOUR CODE HERE ***"
        dict = {}
        if len(food.asList()) == 0:
            return 0
        for foodPos in food.asList():
            dict[mazeDistance(startPosition, foodPos, gameState)] = foodPos
        pos = max(dict.keys())
        newGoal = dict[pos]
        prob = PositionSearchProblem(gameState, start=startPosition, goal=newGoal, warn=False, visualize=False)
        return search.depthFirstSearch(prob)
Ejemplo n.º 4
0
    def findPathToClosestDot(self, gameState):
        "Returns a path (a list of actions) to the closest dot, starting from gameState"
        # Here are some useful elements of the startState
        startPosition = gameState.getPacmanPosition()
        food = gameState.getFood()
        walls = gameState.getWalls()
        problem = AnyFoodSearchProblem(gameState)

        "*** YOUR CODE HERE ***"
        dict = {}
        if len(food.asList()) == 0:
            return 0
        for foodPos in food.asList():
            dict[mazeDistance(startPosition, foodPos, gameState)] = foodPos
        pos = max(dict.keys())
        newGoal = dict[pos]
        prob = PositionSearchProblem(gameState,
                                     start=startPosition,
                                     goal=newGoal,
                                     warn=False,
                                     visualize=False)
        return search.depthFirstSearch(prob)
    def findPathToClosestDot(self, gameState):
        """
        Returns a path (a list of actions) to the closest dot, starting from
        gameState.
        """
        # Here are some useful elements of the startState
        startPosition = gameState.getPacmanPosition()
        food = gameState.getFood().asList()
        walls = gameState.getWalls()
        problem = AnyFoodSearchProblem(gameState)

        # distances = {}
        # for i in food:
        #     distance = mazeDistance(startPosition, i, gameState)
        #     distances[distance] = i

        # min_distance = min(distances.keys())
        # closest_food = distances[min_distance]

        # problem.goal = closest_food
        # print(problem.goal)

        return search.depthFirstSearch(problem)
Ejemplo n.º 6
0
if __name__ == '__main__':

    #
    # The following is the example output shown in the assignment description.
    #

    print('Starting assignment examples\n')

    print("Breadth-first\n")
    print("path from a to a is", breadthFirstSearch('a', 'a', successorsf))
    print("path from a to m is", breadthFirstSearch('a', 'm', successorsf))
    print("path from a to z is", breadthFirstSearch('a', 'z', successorsf))

    print("\nDepth-first\n")
    print("path from a to a is", depthFirstSearch('a', 'a', successorsf))
    print("path from a to m is", depthFirstSearch('a', 'm', successorsf))
    print("path from a to z is", depthFirstSearch('a', 'z', successorsf), '\n')

    print('Finished assignment examples\n')

    # Used for additional unit testing. Imported here because it makes no sense
    # to import this if the file is not run as main.
    #

    from unittest import main, TestCase

    print('Starting additional unit tests\n')

    #
    # Successorsf Tests
Ejemplo n.º 7
0
def getRealDistence(walls,start,goal):
    problem=SingleDistanceProblem(walls,start,goal)
    actions=search.depthFirstSearch(problem)
    return len(actions)
Ejemplo n.º 8
0
state_transitions = {
    'A': ['L', 'B'],
    'B': ['A', 'C'],
    'C': ['B', 'D'],
    'D': ['C', 'E'],
    'E': ['D', 'F'],
    'F': ['E', 'G'],
    'G': ['F', 'H'],
    'H': ['G', 'I'],
    'I': ['H', 'J'],
    'J': ['I', 'K'],
    'K': ['J', 'L'],
    'L': ['K', 'A']
}

if __name__ == '__main__':

    #
    # A few examples of finding paths through the puzzle using BFS and DFS.
    #

    print("From NotInGraph to 'L'")
    printStates(depthFirstSearch('NotInGraph', 'G', successorsf))

    print("\nFrom A to G (DFS): ")
    printStates(depthFirstSearch('A', 'G', successorsf))

    print("\nFrom A to E (BFS): ")
    printStates(breadthFirstSearch('A', 'E', successorsf))
if __name__ == '__main__':
    
    #
    # The following is the example output shown in the assignment description.
    #
    
    print('Starting assignment examples\n')
    
    print("Breadth-first\n")
    print("path from a to a is", breadthFirstSearch('a','a', successorsf))
    print("path from a to m is", breadthFirstSearch('a','m', successorsf))
    print("path from a to z is", breadthFirstSearch('a','z', successorsf))

    print("\nDepth-first\n")
    print("path from a to a is", depthFirstSearch('a','a', successorsf))
    print("path from a to m is", depthFirstSearch('a','m', successorsf))
    print("path from a to z is", depthFirstSearch('a','z', successorsf), '\n')
    
    print('Finished assignment examples\n')


    # Used for additional unit testing. Imported here because it makes no sense
    # to import this if the file is not run as main.
    #
    
    from unittest import main, TestCase


    print('Starting additional unit tests\n')
    
Ejemplo n.º 10
0
 def test_class_example_c(self):
     expected = ['a', 'b', 'e', 'k', 'z']
     actual = depthFirstSearch('a', 'z', successorsf)
     self.assertEquals(actual, expected)
Ejemplo n.º 11
0
 def test_basic_path_e(self):
     expected = ['g', 'o']
     actual = depthFirstSearch('g', 'o', self.successorsf1)
     self.assertEquals(actual, expected)
Ejemplo n.º 12
0
 def test_invalid_types_both(self):
     expected = []
     actual = depthFirstSearch(123, 456, self.successorsf1)
     self.assertEquals(actual, expected)
 def test_class_example_c(self):
     expected = ['a', 'b', 'e', 'k', 'z']
     actual = depthFirstSearch('a', 'z', successorsf)
     self.assertEquals(actual, expected)
 def test_basic_path_f(self):
     expected = ['a', 'c', 'f', 'l']
     actual = depthFirstSearch('a', 'l', self.successorsf1)
     self.assertEquals(actual, expected)
 def test_basic_path_e(self):
     expected = ['g', 'o']
     actual = depthFirstSearch('g', 'o', self.successorsf1)
     self.assertEquals(actual, expected)
 def test_basic_path_d(self):
     expected = ['b', 'e', 'k']
     actual = depthFirstSearch('b', 'k', self.successorsf1)
     self.assertEquals(actual, expected)
 def test_invalid_types_both(self):
     expected = []
     actual = depthFirstSearch(123, 456, self.successorsf1)
     self.assertEquals(actual, expected)
 def test_invalid_end_type(self):
     expected = []
     actual = depthFirstSearch('a', 123, self.successorsf1)
     self.assertEquals(actual, expected)
 def test_does_not_exist_both_states(self):
     expected = []
     actual = depthFirstSearch('DNE', 'DNE', self.successorsf1)
     self.assertEquals(actual, expected)
Ejemplo n.º 20
0
 def test_does_not_exist_both_states(self):
     expected = []
     actual = depthFirstSearch('DNE', 'DNE', self.successorsf1)
     self.assertEquals(actual, expected)
Ejemplo n.º 21
0
 def test_invalid_end_type(self):
     expected = []
     actual = depthFirstSearch('a', 123, self.successorsf1)
     self.assertEquals(actual, expected)
 def test_none_both(self):
     expected = []
     actual = depthFirstSearch(None, None, successorsf)
     self.assertEquals(actual, expected)
Ejemplo n.º 23
0
 def test_basic_path_d(self):
     expected = ['b', 'e', 'k']
     actual = depthFirstSearch('b', 'k', self.successorsf1)
     self.assertEquals(actual, expected)
Ejemplo n.º 24
0
 def runTest(self):
     print "Path result for DFS:",search.depthFirstSearch(self)
     print "Path result for BFS:",search.breadthFirstSearch(self)
     print "Path result for UCS:",search.uniformCostSearch(self)
     #print "Path result for A*:",search.aStarSearch(self,search.nullHeuristic)
     print "Path result for A* with letter heuristic:",search.aStarSearch(self,letterHeuristic)
Ejemplo n.º 25
0
 def test_basic_path_f(self):
     expected = ['a', 'c', 'f', 'l']
     actual = depthFirstSearch('a', 'l', self.successorsf1)
     self.assertEquals(actual, expected)
Ejemplo n.º 26
0
		solution.display()
	else:
		print 'No solution found!!'
	'''



	n = 5
	strategy = search.astar

	puzzle = game.NPuzzle(n)
	puzzle.randomStartState()
	puzzle.randomGoalState(47)
	puzzle.startState.display()
	puzzle.goalState.display()

	if strategy == search.bfs:
		solution = search.breadthFirstSearch(puzzle)
	elif strategy == search.dfs:
		solution  = search.depthFirstSearch(puzzle)
	elif strategy == search.ucs:
		solution  = search.uniformCostSearch(puzzle)
	elif strategy == search.dls:
		solution = search.depthLimitedSearch(puzzle,6)
	elif strategy == search.astar:
		solution = search.astar(puzzle, game.manhattanDistance)

	if solution != None:
		solution.display()
	else:
		print 'No solution found!!'
Ejemplo n.º 27
0
 def test_none_both(self):
     expected = []
     actual = depthFirstSearch(None, None, successorsf)
     self.assertEquals(actual, expected)
Ejemplo n.º 28
0
 def getAction(self, state):
     problem = PositionSearchProblem(state)
     pos = search.depthFirstSearch(problem)
     print(pos)
     return pos[0]
Ejemplo n.º 29
0
 def __init__(self):
     self.searchFunction = lambda prob: search.depthFirstSearch(prob)
     self.searchType = PositionSearchProblem
Ejemplo n.º 30
0
def elegir_algoritmo(problem):
    ######################################################
    #############-----ELEGIR ALGORITMO----################
    ######################################################

    print('     *****************************************************')
    print('     *                                                   *')
    print('     *       (1) --> DFS   (Depth First Search)          *')
    print('     *       (2) --> BFS   (Breadth First Search)        *')
    print('     *       (3) --> IDS   (Iterative deepening search)  *')
    print('     *       (4) --> BS    (Bidirectional search)        *')
    print('     *       (5) --> A*    (A* Search - astar)           *')
    print('     *                                                   *')
    print('     *****************************************************')
    while True:

        data = input('Elija un ALGORITMO (1,2,3,4,5): ')
        if data not in (1, 2, 3, 4, 5):
            print('Elija un numero correcto')
        else:
            data = int(data)
            if (data == 1):
                inicio = time.time()
                path = search.depthFirstSearch(problem)
                fin = time.time()
                print(fin - inicio)
                return path
            if (data == 2):
                inicio = time.time()
                path = search.breadthFirstSearch(problem)
                fin = time.time()
                print(fin - inicio)
                return path
            if (data == 3):
                inicio = time.time()
                path = search.iDeepeningSearch(problem)
                fin = time.time()
                print(fin - inicio)
                return path
            if (data == 4):
                inicio = time.time()
                path = search.BidirectionalSearch(problem)
                fin = time.time()
                print(fin - inicio)
                return path
            if (data == 5):
                print('         *********************************************')
                print('         *                                           *')
                print('         *       (0) --> Null Heuristic              *')
                print('         *       (1) --> Manhattan Heuristic         *')
                print('         *       (2) --> Euclidean Heuristic         *')
                print('         *                                           *')
                print('         *********************************************')
                while True:
                    h = input('Elija una Heuristica (0 , 1 , 2): ')
                    h = int(h)
                    if (h == 0):
                        inicio = time.time()
                        path = search.aStarSearch(problem,
                                                  search.nullHeuristic)
                        fin = time.time()
                        print(fin - inicio)
                        return path
                    if (h == 1):
                        inicio = time.time()
                        path = search.aStarSearch(problem,
                                                  search.manhattan_distance)
                        fin = time.time()
                        print(fin - inicio)
                        return path
                    if (h == 2):
                        inicio = time.time()
                        path = search.aStarSearch(problem,
                                                  search.euclideanHeuristic)
                        fin = time.time()
                        print(fin - inicio)
                        return path
                    break
            break
Ejemplo n.º 31
0
state_transitions = {
    "A": ["L", "B"],
    "B": ["A", "C"],
    "C": ["B", "D"],
    "D": ["C", "E"],
    "E": ["D", "F"],
    "F": ["E", "G"],
    "G": ["F", "H"],
    "H": ["G", "I"],
    "I": ["H", "J"],
    "J": ["I", "K"],
    "K": ["J", "L"],
    "L": ["K", "A"],
}


if __name__ == "__main__":

    #
    # A few examples of finding paths through the puzzle using BFS and DFS.
    #

    print ("From NotInGraph to 'L'")
    printStates(depthFirstSearch("NotInGraph", "G", successorsf))

    print ("\nFrom A to G (DFS): ")
    printStates(depthFirstSearch("A", "G", successorsf))

    print ("\nFrom A to E (BFS): ")
    printStates(breadthFirstSearch("A", "E", successorsf))
Ejemplo n.º 32
0
 def __init__(self):
     self.searchFunction = lambda prob: search.depthFirstSearch(prob)
     self.searchType = FoodSearchProblem