Professional Documents
Culture Documents
"E": {"B": 4}
}
class graphProblem:
def __init__(self,initial,goal,graph):
self.initial=initial
self.goal=goal
self.graph=graph
def actions(self,state):
return list(self.graph[state].keys())
def result(self,state,action):
return action
def goal_test(self,state):
def path_cost(self,cost_so_far,state1,action,state2):
def __init__(self,state,parent=None,action=None,path_cost=0):
self.state=state
self.parent=parent
self.action=action
self.path_cost=path_cost
def expand(self,graphProblem):
return [self.child_node(graphProblem,action)
def child_node(self,graphProblem,action):
next_state=graphProblem.result(self.state,action)
return Node(next_state,self,action,
graphProblem.path_cost(self.path_cost,self.state,action,next_state))
def path(self):
while node:
path_back.append(node)
node = node.parent
return list(reversed(path_back))
def solution(self):
def __init__(self,pop_index):
self.queue = []
self.pop_index=pop_index
self.queue.append(item)
self.queue.append(item)
self.queue.sort(key=f)
self.queue.extend(items)
def pop(self):
if len(self.queue) > 0:
return self.queue.pop(self.pop_index)
else:
def printQueue(self):
def __len__(self):
return len(self.queue)
def __contains__(self, item):
def best_first_search(problem,f,pop_index=0):
node = Node(problem.initial)
if problem.goal_test(node.state):
return state
frontier = Queue(pop_index)
frontier.sortAppend(node,f)
explored = set()
while frontier:
frontier.printQueue()
node = frontier.pop()
if problem.goal_test(node.state):
return node
explored.add(node.state)
frontier.sortAppend(child,f)
return None
def ucs(problem):
return best_first_search(problem, lambda node:node.path_cost)
def a_star(problem):
def gbfs(problem):
problem = graphProblem("S","G",graph)
print("=======UCS========")
goalnode = gbfs(problem)
print (goalnode.solution())
print("=======GBFS========")
goalnode = gbfs(problem)
print (goalnode.solution())
print("\n========A*========")
goalnode = a_star(problem)
print(goalnode.solution())