test_aula3 finished

Signed-off-by: Tiago Garcia <tiago.rgarcia@ua.pt>
This commit is contained in:
Tiago Garcia 2024-10-12 17:53:56 +01:00
parent 790453a712
commit 7f5313608e
Signed by: TiagoRG
GPG Key ID: DFCD48E3F420DB42
1 changed files with 26 additions and 7 deletions

View File

@ -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):
@ -76,10 +77,20 @@ class SearchTree:
# construtor
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