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

AI

Ai program

Uploaded by

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

AI

Ai program

Uploaded by

sutarlokesh750
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

1.

Implementation of uniformed search techniques like,


i)Breadth first search
graph={

'A':['B','C'],
'B':['D','E'],
'C':['F'],
'D':[],
'E':['F'],

'F':[]
}
visited=[]
queue=[]

def bfs(visited,graph,node):
visited.append(node)
queue.append(node)
while queue:

s=queue.pop(0)
print(s,end=" ")
for neighbour in graph[s]:
if neighbour not in visited:
visited.append(neighbour)
queue.append(neighbour)

bfs(visited,graph,'A')

OUTPUT:

===================== RESTART: C:\Users\HP\Documents\bfs.py ====================

ABCDEF
ii) Deapth First Search
graph={

'1':['2','3'],
'2':['4','5'],
'3':['6'],
'4':[],

'5':['6'],
'6':[]
}
visited=set()

def dfs(visited,graph,node):
if node not in visited:
print(node)
visited.add(node)
for neighbour in graph[node]:

dfs(visited,graph,neighbour)
print("following is the depth-first search")
dfs(visited,graph,'1')

OUTPUT:
= RESTART: C:\Users\HP\Documents\dfs.py

following is the depth-first search

1
2
4

5
6
3
2.Implementation of informed (Heuristic) search techniques like
i)Best first Search
from queue import PriorityQueue

v=14
graph=[[]for i in range(v)]
def best_first_search(actual_Src,target,n):
visited=[False]*n
pq=PriorityQueue()

pq.put((0,actual_Src))
visited[actual_Src]=True
while pq.empty()==False:
u=pq.get()[1]

print(u,end=" ")
if u == target:
break
for v,c in graph[u]:

if visited[v] == False:
visited[v]=True
pq.put((c,v))
print()
def addedge(x,y,cost):

graph[x].append((y,cost))
graph[y].append((x,cost))
addedge(0,1,3)
addedge(0,2,6)

addedge(0,3,5)
addedge(1,4,9)
addedge(1,5,8)
addedge(2,6,12)
addedge(2,7,14)
addedge(3,8,7)

addedge(8,9,5)
addedge(8,10,6)
addedge(9,11,1)
addedge(9,12,10)

addedge(9,13,2)
source=0
target=9
best_first_search(source,target,v)

OUTPUT:

= RESTART: C:\Users\HP\Documents\best first search.py

013289
ii)Branch and Bound Search
from sys import maxsize
from itertools import permutations

V=4
def branchandboundsearch(graph,s):
vertex = []
for i in range(V):

if i != s:
vertex.append(i)
min_path = maxsize
next_permutation=permutations(vertex)

for i in next_permutation:
current_pathweight = 0
k=s
for j in i:
current_pathweight += graph[k][j]

k=j
current_pathweight += graph[k][s]
min_path = min(min_path, current_pathweight)
return min_path

if __name__ == "__main__":
graph = [[0, 10, 15, 20],[10, 0, 35, 25],
[15, 35, 0, 30], [20, 25, 30, 0]]
s=0

print(branchandboundsearch(graph,s))

OUTPUT:
= RESTART: C:\Users\HP\Documents\branch.py

80
iii)A* Search
def aStarAlgo(start_node, stop_node):
open_set = set(start_node)

closed_set = set()
g = {}
parents = {}
g[start_node] = 0

parents[start_node] = start_node
while len(open_set) > 0:
n = None
for v in open_set:

if n == None or g[v] + heuristic(v) < g[n] + heuristic(n):


n=v
if n == stop_node or Graph_nodes[n] == None:
pass
else:

for (m, weight) in get_neighbors(n):


if m not in open_set and m not in closed_set:
open_set.add(m)
parents[m] = n

g[m] = g[n] + weight


else:
if g[m] > g[n] + weight:
g[m] = g[n] + weight

parents[m] = n
if m in closed_set:
closed_set.remove(m)
open_set.add(m)

if n == None:
print('Path does not exist!')
return None
if n == stop_node:

path = []
while parents[n] != n:
path.append(n)
n = parents[n]

path.append(start_node)
path.reverse()
print('Path found: {}'.format(path))
return path

open_set.remove(n)
closed_set.add(n)
print('Path does not exist!')
return None
def get_neighbors(v):

if v in Graph_nodes:
return Graph_nodes[v]
else:
return None

def heuristic(n):
H_dist = {
'A': 11,
'B': 6,

'C': 99,
'D': 1,
'E': 7,
'G': 0,

}
return H_dist[n]
Graph_nodes = {
'A': [('B', 2), ('E', 3)],

'B': [('C', 1),('G', 9)],


'C': None,
'E': [('D', 6)],
'D': [('G', 1)],

}
aStarAlgo('A', 'G')

OUTPUT:

= RESTART: C:\Users\HP\Documents\Astart.py

Path found: ['A', 'E', 'D', 'G']


iv)Hill Climbing search
import random
def objective_function(x):

return -(x**3)
def hill_climbing(problem,initial_solution,step_size,max_iteractions):
current_solution=initial_solution
current_value=problem(current_solution)

for _ in range(max_iteractions):
neighbor=current_solution+random.uniform(-step_size,step_size)
neighbor_value=problem(neighbor)
if neighbor_value>current_value:

current_solution=neighbor
current_value=neighbor_value
return current_solution,current_value
initial_solution=10
step_size=0.1

max_iteractions=100
best_solution,best_value=hill_climbing(objective_function,initial_solution,step_size,max_ite
ractions)
print("Best solution:",best_solution)

print("Best value:",best_value)

OUTPUT:

= RESTART: C:\Users\HP\Documents\hillclimbing.py
Best solution: 9.975364683903177
Best value: -992.6275971837849
V)AO* Search

import heapq

class Node:

def __init__(self, state, parent=None, cost=0, heuristic=0):

self.state = state

self.parent = parent

self.cost = cost

self.heuristic = heuristic

def total_cost(self):

return self.cost + self.heuristic

def ao_star(initial_state, goal_state, successors, heuristic, max_cost=float('inf')):

initial_node = Node(initial_state, cost=0, heuristic=heuristic(initial_state))

frontier = [(initial_node.total_cost(), initial_node)]

explored = set()

while frontier:

_, current_node = heapq.heappop(frontier)

if current_node.state == goal_state:

return reconstruct_path(current_node)

explored.add(current_node.state)

for action, child_state, step_cost in successors(current_node.state):

if child_state not in explored:

child_node = Node(child_state, parent=current_node, cost=current_node.cost + step_cost,


heuristic=heuristic(child_state))

total_cost = child_node.total_cost()
if total_cost <= max_cost:

heapq.heappush(frontier, (total_cost, child_node))

return None

def reconstruct_path(node):

path = []

while node:

path.insert(0, node.state)

node = node.parent

return path

def successors(state):

return [('action1', 'state1', 1), ('action2', 'state2', 2)]

def heuristic(state):

return 0

initial_state = 'start'

goal_state = 'goal'

result = ao_star(initial_state, goal_state, successors, heuristic)

print(result)

OUTPUT:

= RESTART: C:\Users\HP\Documents\aostar.py

None

You might also like