0% found this document useful (0 votes)
13 views

AIML (1st 2 PRGS)

The document describes an implementation of the A* search algorithm in Python. It includes definitions for a Graph class that represents a graph and heuristic values for nodes. The Graph class implements the A* search algorithm through its applyAOStar method. It also includes examples that initialize Graph objects with sample graphs and heuristic values, run A* search on them, and print the solution graphs.

Uploaded by

Samar Fathima
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

AIML (1st 2 PRGS)

The document describes an implementation of the A* search algorithm in Python. It includes definitions for a Graph class that represents a graph and heuristic values for nodes. The Graph class implements the A* search algorithm through its applyAOStar method. It also includes examples that initialize Graph objects with sample graphs and heuristic values, run A* search on them, and print the solution graphs.

Uploaded by

Samar Fathima
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 5

PROGRAM-1

from queue import PriorityQueue

graph_nodes = {

'S': [('B', 4), ('C', 3)],

'B': [('F', 5), ('E', 12)],

'C': [('E', 10), ('D', 7)],

'D': [('E', 2)],

'E': [('G', 5)],

'F': [('G', 16)],

def heuristic(n):

H_dist = {

'S': 14,

'B': 12,

'C': 11,

'D': 6,

'E': 4,

'F': 11,

'G': 0

return H_dist[n]

def astar(start, goal):

pq = PriorityQueue()

pq.put((0, start))

visited = set()

g_score = {node: float('inf') for node in graph_nodes}

g_score[start] = 0

f_score = {node: float('inf') for node in graph_nodes}

f_score[start] = heuristic(start)

g_score['G'] = float('inf') # Initialize G in g_score

f_score['G'] = float('inf') # Initialize G in f_score

while not pq.empty():

current = pq.get()[1]

if current == goal:

return g_score[current]

visited.add(current)

for neighbor, distance in graph_nodes[current]:

tentative_g_score = g_score[current] + distance

if tentative_g_score < g_score[neighbor]:


g_score[neighbor] = tentative_g_score

f_score[neighbor] = tentative_g_score + heuristic(neighbor)

if neighbor not in visited:

pq.put((f_score[neighbor], neighbor))

return float('inf')

start_node = 'S'

goal_node = 'G'

result = astar(start_node, goal_node)

print(f"The shortest path cost from {start_node} to {goal_node} is: {result}")


PROGRAM-2
class Graph:

def __init__(self, graph, heuristicNodeList, startNode):

self.graph = graph

self.H = heuristicNodeList

self.start = startNode

self.parent = {}

self.status = {}

self.solutionGraph = {}

def applyAOStar(self):

self.aoStar(self.start, False)

def getNeighbors(self, v):

return self.graph.get(v, '')

def getStatus(self, v):

return self.status.get(v, 0)

def setStatus(self, v, val):

self.status[v] = val

def getHeuristicNodeValue(self, n):

return self.H.get(n, 0)

def setHeuristicNodeValue(self, n, value):

self.H[n] = value

def printSolution(self):

print("Solution Graph:")

print("Start Node:", self.start)

print(self.solutionGraph)

def computeMinimumCostChildNodes(self, v):

minimumCost = float('inf')

costToChildNodeListDict = {}

for nodeInfoTupleList in self.getNeighbors(v):

cost = sum(self.getHeuristicNodeValue(c) + weight for c, weight in nodeInfoTupleList)

if cost < minimumCost:

minimumCost = cost
costToChildNodeListDict[minimumCost] = [c for c, _ in nodeInfoTupleList]

if minimumCost == float('inf'):

# No neighbors for the current node, set an appropriate default value

return 0, []

return minimumCost, costToChildNodeListDict[minimumCost]

def aoStar(self, v, backTracking):

if self.getStatus(v) >= 0:

minimumCost, childNodeList = self.computeMinimumCostChildNodes(v)

self.setHeuristicNodeValue(v, minimumCost)

self.setStatus(v, len(childNodeList))

solved = all(self.getStatus(childNode) != -1 for childNode in childNodeList)

if solved:

self.setStatus(v, -1)

self.solutionGraph[v] = childNodeList

if v != self.start and not backTracking:

self.aoStar(self.parent[v], True)

if not backTracking:

for childNode in childNodeList:

self.setStatus(childNode, 0)

self.parent[childNode] = v

self.aoStar(childNode, False)

# Example 1

h1 = {'A': 1, 'B': 6, 'C': 2, 'D': 12, 'E': 2, 'F': 1, 'G': 5, 'H': 7, 'I': 7, 'J': 1, 'T': 3}

graph1 = {

'A': [[('B', 1), ('C', 1)], [('D', 1)]],

'B': [[('G', 1)], [('H', 1)]],

'C': [[('J', 1)]],

'D': [[('E', 1), ('F', 1)]],

'G': [[('I', 1)]]

}
G1 = Graph(graph1, h1, 'A')

G1.applyAOStar()

G1.printSolution()

# Example 2

h2 = {'A': 1, 'B': 6, 'C': 12, 'D': 10, 'E': 4, 'F': 4, 'G': 5, 'H': 7}

graph2 = {

'A': [[('B', 1), ('C', 1)], [('D', 1)]],

'B': [[('G', 1)], [('H', 1)]],

'D': [[('E', 1), ('F', 1)]]

G2 = Graph(graph2, h2, 'A')

G2.applyAOStar()

G2.printSolution()

You might also like