diff --git a/tree_search.py b/tree_search.py index d616db9..11fc70d 100644 --- a/tree_search.py +++ b/tree_search.py @@ -1,6 +1,6 @@ # Module: tree_search -# +# # This module provides a set o classes for automated # problem solving through tree search: # SearchDomain - problem domains @@ -62,9 +62,10 @@ class SearchProblem: # Nos de uma arvore de pesquisa class SearchNode: - def __init__(self,state,parent): + def __init__(self,state,parent, depth): self.state = state self.parent = parent + self.depth = depth def __str__(self): return "no(" + str(self.state) + "," + str(self.parent) + ")" def __repr__(self): @@ -74,12 +75,22 @@ class SearchNode: class SearchTree: # construtor - def __init__(self,problem, strategy='breadth'): + def __init__(self,problem, strategy='breadth'): self.problem = problem - root = SearchNode(problem.initial, None) + root = SearchNode(problem.initial, None, 0) self.open_nodes = [root] self.strategy = strategy self.solution = None + self.terminals = 0 + self.non_terminals = 0 + + @property + def length(self): + return self.solution.depth if self.solution else None + + @property + def avg_branching(self): + return ((self.terminals + self.non_terminals) - 1) / self.non_terminals if self.non_terminals > 0 else None # obter o caminho (sequencia de estados) da raiz ate um no def get_path(self,node): @@ -90,17 +101,25 @@ class SearchTree: return(path) # procurar a solucao - def search(self): + def search(self,limit=None): while self.open_nodes != []: + self.terminals = len(self.open_nodes) node = self.open_nodes.pop(0) if self.problem.goal_test(node.state): self.solution = node return self.get_path(node) + + self.non_terminals += 1 lnewnodes = [] for a in self.problem.domain.actions(node.state): newstate = self.problem.domain.result(node.state,a) - newnode = SearchNode(newstate,node) - lnewnodes.append(newnode) + if newstate not in self.get_path(node): + newnode = SearchNode(newstate,node,node.depth+1) + if limit != None and self.strategy == 'depth': + if newnode.depth <= limit: + lnewnodes.append(newnode) + else: + lnewnodes.append(newnode) self.add_to_open(lnewnodes) return None