示例#1
0
文件: Ex39test.py 项目: ecejjar/AI
    def testProblem(self):
        initial = 1
        successor = lambda x : (2*x, 2*x + 1)
        cost = lambda x, y : 1
        
        goal = 8    # goal must be on the leftmost branch of the tree!!
        problem = Problem(initial, goal, successor, cost)
        
        solver = ProblemSolver()
        solver.solve(problem, ProblemSolver.depthFirstGenerator(successor))
        self.assertTrue(solver.solved(problem))
        self.assertEqual(
            solver.solution, [1, 2, 4, 8],
            "Solution found using depth-first search is " + str(solver.solution))

        goal = 10
        problem = Problem(initial, goal, successor, cost)
        solver = ProblemSolver()
        solver.solve(problem, ProblemSolver.breadthFirstGenerator(successor))
        self.assertTrue(solver.solved(problem))
        self.assertEqual(
            solver.solution, [1, 2, 5, 10],
            "Solution found using breadth-first search is " + str(solver.solution))

        goal = 10
        problem = Problem(initial, goal, successor, cost)
        solver = ProblemSolver()
        solver.solve(problem, ProblemSolver.depthLimitedGenerator(successor, 4))
        self.assertTrue(solver.solved(problem))
        self.assertEqual(
            solver.solution, [1, 2, 5, 10],
            "Solution found using depth-limited search is " + str(solver.solution))

        goal = 10
        problem = Problem(initial, goal, successor, cost)
        solver = ProblemSolver()
        solver.solve(problem, ProblemSolver.iterativeDeepeningGenerator(successor))
        self.assertTrue(solver.solved(problem))
        self.assertEqual(
            solver.solution, [1, 2, 5, 10],
            "Solution found using IDDF search is " + str(solver.solution))

        goal = 10
        successor = \
            lambda x: (random() < 0.5 and (2*x, 2*x + 1)) \
            or (max(1, int(x/2)), 2*x, 2*x + 1)
        problem = Problem(initial, goal, successor, cost)
        solver = ProblemSolver()
        solver.solve(problem, ProblemSolver.breadthFirstGenerator(successor), True)
        self.assertTrue(solver.solved(problem))
        self.assertEqual(
            solver.solution, [1, 2, 5, 10],
            "Solution found using breadth-first *graph* search is " + str(solver.solution))

        goal = 32
        successor = \
            lambda x: (random() < 0.5 and (2*x, 2*x + 1)) \
            or (max(1, int(x/2)), 2*x, 2*x + 1)
        problem = Problem(initial, goal, successor, cost)
        solver = ProblemSolver()
        solver.solve(problem, ProblemSolver.iterativeDeepeningGenerator(successor), True)
        self.assertTrue(solver.solved(problem))
        self.assertEqual(
            solver.solution, [1, 2, 4, 8, 16, 32],
            "Solution found using IDDF *graph* search is " + str(solver.solution))