0% found this document useful (0 votes)
18 views10 pages

Write A Program To Implement The Heuristic Search

The document contains multiple Python implementations for various algorithms including Heuristic Search, A*, AO*, Water-Jug Problem, Alpha-Beta Pruning, and the 8-Queens Problem. Each section provides code examples demonstrating the functionality of the respective algorithms. The implementations are designed to solve specific problems using appropriate data structures and algorithms.

Uploaded by

ariseofsun
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views10 pages

Write A Program To Implement The Heuristic Search

The document contains multiple Python implementations for various algorithms including Heuristic Search, A*, AO*, Water-Jug Problem, Alpha-Beta Pruning, and the 8-Queens Problem. Each section provides code examples demonstrating the functionality of the respective algorithms. The implementations are designed to solve specific problems using appropriate data structures and algorithms.

Uploaded by

ariseofsun
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

AIM: Write a program to implement the Heuristic Search.

import heapq

class Graph:
def __init__(self):
# Graph represented as an adjacency list with costs
self.graph = {}
# Heuristic values for each node (used to guide the search)
self.heuristic = {}

# Function to add an edge to the graph


def add_edge(self, u, v, cost):
if u not in self.graph:
self.graph[u] = []
if v not in self.graph:
self.graph[v] = []
self.graph[u].append((v, cost))
self.graph[v].append((u, cost)) # For undirected graph

# Function to perform A* search


def a_star(self, start, goal):
open_list = []
closed_list = set()
g_costs = {start: 0}
parents = {start: None}

heapq.heappush(open_list, (self.heuristic[start], start))

while open_list:
_, current_node = heapq.heappop(open_list)

if current_node == goal:
path = []
while current_node is not None:
path.append(current_node)
current_node = parents[current_node]
return path[::-1] # Return reversed path

closed_list.add(current_node)

for neighbor, cost in self.graph.get(current_node, []):


if neighbor in closed_list:
continue
tentative_g_cost = g_costs[current_node] + cost

if neighbor not in g_costs or tentative_g_cost < g_costs[neighbor]:


g_costs[neighbor] = tentative_g_cost
total_cost = tentative_g_cost + self.heuristic.get(neighbor, float('inf'))
heapq.heappush(open_list, (total_cost, neighbor))
parents[neighbor] = current_node

return None # No path found

# Example usage
if __name__ == "__main__":
g = Graph()

# Add edges (undirected graph with costs)


g.add_edge('A', 'B', 1)
g.add_edge('A', 'C', 4)
g.add_edge('B', 'D', 2)
g.add_edge('B', 'E', 5)
g.add_edge('C', 'F', 1)
g.add_edge('D', 'G', 3)
g.add_edge('E', 'G', 1)
g.add_edge('F', 'G', 2)

# Heuristic values for each node (to goal 'G')


g.heuristic = {
'A': 7,
'B': 6,
'C': 2,
'D': 4,
'E': 3,
'F': 5,
'G': 0
}

# Run A* search
path = g.a_star('A', 'G')

if path:
print("Path found:", " -> ".join(path))
else:
print("No path found.")
AIM: Write a python program to implement A* and AO* algorithm. (Ex: find
the shortest path).

import heapq
class Graph:
def __init__(self):
self.graph = {}

def add_edge(self, node, neighbor, cost):


if node not in self.graph:
self.graph[node] = []
self.graph[node].append((neighbor, cost))

def astar(self, start, goal, heuristic):


open_list = []
heapq.heappush(open_list, (heuristic[start], 0, start, [])) # (f(n), g(n), node, path)
closed_set = set()

while open_list:
_, cost, current, path = heapq.heappop(open_list)

if current in closed_set:
continue

path = path + [current]

if current == goal:
return path, cost

closed_set.add(current)

for neighbor, edge_cost in self.graph.get(current, []):


if neighbor not in closed_set:
total_cost = cost + edge_cost
estimated_cost = total_cost + heuristic.get(neighbor, float('inf'))
heapq.heappush(open_list, (estimated_cost, total_cost, neighbor, path))

return None, float("inf")

# Example usage of A*
print("=== A* Algorithm ===")
g = Graph()
g.add_edge('A', 'B', 1)
g.add_edge('A', 'C', 4)
g.add_edge('B', 'C', 2)
g.add_edge('B', 'D', 5)
g.add_edge('C', 'D', 1)

heuristic = {'A': 7, 'B': 6, 'C': 2, 'D': 0} # Estimated cost to goal (D)

path, cost = g.astar('A', 'D', heuristic)


print(f"A* Path: {path}, Cost: {cost}\n")

class AOStarGraph:
def __init__(self):
self.graph = {} # Node: [[group1], [group2], ...]
self.heuristic = {} # Heuristic values per node

def add_node(self, node, neighbors):


self.graph[node] = neighbors

def set_heuristic(self, heuristic):


self.heuristic = heuristic

def ao_star(self, node):


if node not in self.graph or not self.graph[node]:
return self.heuristic.get(node, 0)
min_cost = float('inf')
for group in self.graph[node]:
cost = sum(self.ao_star(n) for n in group) + self.heuristic.get(node, 0)
if cost < min_cost:
min_cost = cost

return min_cost

print("=== AO* Algorithm ===")


ag = AOStarGraph()
ag.add_node('A', [['B', 'C'], ['D']])
ag.add_node('B', [['E'], ['F']])
ag.add_node('C', [['G']])
ag.add_node('D', [['H']])
ag.set_heuristic({
'E': 5, 'F': 3, 'G': 2, 'H': 4,
'A': 1, 'B': 1, 'C': 2, 'D': 2
})

print(f"AO* Minimum Cost from A: {ag.ao_star('A')}")


AIM: Write a Program to Implement Water-Jug problem using Python.
from collections import deque
def water_jug_bfs(jug1, jug2, target):
visited = set()
queue = deque([(0, 0)]) # Initial state (0,0)

while queue:
state = queue.popleft()
a, b = state

if state in visited:
continue
visited.add(state)

print(f"Jug1: {a}L, Jug2: {b}L") # Print the current state


if a == target or b == target:
print(" Solution Found!")
return

# All possible operations from current state


operations = set([
(jug1, b), # Fill Jug1
(a, jug2), # Fill Jug2
(0, b), # Empty Jug1
(a, 0), # Empty Jug2

# Pour Jug1 -> Jug2


(a - min(a, jug2 - b), b + min(a, jug2 - b)),

# Pour Jug2 -> Jug1


(a + min(b, jug1 - a), b - min(b, jug1 - a))
])
for new_state in operations:
if new_state not in visited:
queue.append(new_state)


print(" No solution found.")
jug1_capacity = 4
jug2_capacity = 3
target_amount = 2

print("Steps to reach target:")


water_jug_bfs(jug1_capacity, jug2_capacity, target_amount)
AIM: Write a Program to Implement Alpha-Beta Pruning using Python.

import math

def alpha_beta_pruning(depth, node_index, maximizing_player, values,


alpha, beta):

if depth == 3:

return values[node_index]

if maximizing_player:

max_eval = -math.inf

for i in range(2):

eval = alpha_beta_pruning(depth + 1, node_index * 2 + i, False,


values, alpha, beta)

max_eval = max(max_eval, eval)

alpha = max(alpha, eval)

if beta <= alpha:

break # Beta Cutoff

return max_eval

else:

min_eval = math.inf

for i in range(2):
eval = alpha_beta_pruning(depth + 1, node_index * 2 + i, True,
values, alpha, beta)

min_eval = min(min_eval, eval)

beta = min(beta, eval)

if beta <= alpha:

break # Alpha Cutoff

return min_eval

values = [3, 5, 6, 9, 1, 2, 0, -1] # Leaf node values

optimal_value = alpha_beta_pruning(0, 0, True, values, -math.inf,


math.inf)

print(f"Optimal Value: {optimal_value}")

AIM: Write a Program to implement 8-Queens Problem using Python.

def print_solution(board):

for row in board:

print(" ".join("Q" if col else "." for col in row))

print("\n")
def is_safe(board, row, col, n):

for i in range(col):

if board[row][i]:

return False

for i, j in zip(range(row, -1, -1), range(col, -1, -1)):

if board[i][j]:

return False

for i, j in zip(range(row, n, 1), range(col, -1, -1)):

if board[i][j]:

return False

return True

def solve_n_queens_util(board, col, n):

if col >= n:

print_solution(board)

return True
res = False

for i in range(n):

if is_safe(board, i, col, n):

board[i][col] = True

res = solve_n_queens_util(board, col + 1, n) or res

board[i][col] = False

return res

def solve_n_queens(n):

board = [[False] * n for _ in range(n)]

if not solve_n_queens_util(board, 0, n):

print("No solution exists")

# Example usage

solve_n_queens(8)

Output:
Q.......

......Q.

....Q...

.......Q

.Q......

...Q....

.....Q..

..Q.....

You might also like