0% found this document useful (0 votes)
4 views14 pages

AI Print

The document outlines practical implementations of various search techniques in artificial intelligence, including uninformed searches like Breadth First Search (BFS) and Depth First Search (DFS), as well as informed searches such as Best First Search, A* Search, and Hill Climbing. Each section contains Python code examples demonstrating the algorithms and their functionalities. Additionally, it includes a practical implementation of the Branch and Bound and AO* Search techniques.

Uploaded by

trisharanwagh1
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)
4 views14 pages

AI Print

The document outlines practical implementations of various search techniques in artificial intelligence, including uninformed searches like Breadth First Search (BFS) and Depth First Search (DFS), as well as informed searches such as Best First Search, A* Search, and Hill Climbing. Each section contains Python code examples demonstrating the algorithms and their functionalities. Additionally, it includes a practical implementation of the Branch and Bound and AO* Search techniques.

Uploaded by

trisharanwagh1
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/ 14

S.S. and S.

S’s
Vidhyadhan Commerce college Wadel Road Dhule
Department of Computer Science
Class:- SYBCA SEM -IV Subject BCA 407 Artificial Intelligence
Practical 1. Implementation of uninformed search techniques like, i) Breadth first Search

Student Name _____________________________________________________________


*************************************************************************
# BFS algorithm in Python
import collections
# BFS algorithm
def bfs(graph, root):
visited, queue = set(), collections.deque([root])
visited.add(root)
while queue:
# Dequeue a vertex from queue
vertex = queue.popleft()
print(str(vertex) + " ", end="")
# If not visited, mark it as visited, and
# enqueue it
for neighbour in graph[vertex]:
if neighbour not in visited:
visited.add(neighbour)
queue.append(neighbour)
if __name__ == '__main__':
graph = {0: [1, 2], 1: [2], 2: [3], 3: [1, 2]}
print("Following is Breadth First Traversal: ")
bfs(graph, 0)

OUTPUT
S.S. and S. S’s
Vidhyadhan Commerce college Wadel Road Dhule
Department of Computer Science
Class:- SYBCA SEM -IV Subject BCA 407 Artificial Intelligence
Practical 1. Implementation of uninformed search techniques like, i) Breadth first Search

Student Name _____________________________________________________________


*************************************************************************
# Python3 program to print DFS traversal
# from a given graph
from collections import defaultdict
# This class represents a directed graph using
# adjacency list representation
class Graph:
# Constructor
def __init__(self):
# Default dictionary to store graph
self.graph = defaultdict(list)
# Function to add an edge to graph
def addEdge(self, u, v):
self.graph[u].append(v)
# A function used by DFS
def DFSUtil(self, v, visited):
visited.add(v)
print(v, end=' ')
for neighbour in self.graph[v]:
if neighbour not in visited:
self.DFSUtil(neighbour, visited)
def DFS(self, v):
# Create a set to store visited vertices
visited = set()

# Call the recursive helper function


# to print DFS traversal
self.DFSUtil(v, visited)
# Driver's code
if __name__ == "__main__":
g = Graph()
g.addEdge(0, 1)
g.addEdge(0, 2)
g.addEdge(1, 2)
g.addEdge(2, 0)
g.addEdge(2, 3)
g.addEdge(3, 3)
print("Following is Depth First Traversal (starting from vertex 2)")
# Function call
g.DFS(2)
S.S. and S. S’s
Vidhyadhan Commerce college Wadel Road Dhule
Department of Computer Science
Class:- SYBCA SEM -IV Subject BCA 407 Artificial Intelligence
Practical 2. Implementation of informed (Heuristic) search techniques like
Student Name _____________________________________________________________

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]
# Displaying the path having lowest cost
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)
Vidhyadhan Commerce college Wadel Road Dhule
Department of Computer Science
Class:- SYBCA SEM -IV Subject BCA 407 Artificial Intelligence
Practical 2. Implementation of informed (Heuristic) search techniques like Branch and
Bound Search
Student Name _____________________________________________________________

import itertools
def evaluate_subset(subset):
# Placeholder function to evaluate the performance of a feature subset
# Replace this with your own evaluation metric or scoring function
# Calculate the performance metric for the subset and return the score
return len(subset)

def branch_and_bound(features, k):


n = len(features)
best_subset = []
best_score = 0.0

def evaluate_branch(subset):
nonlocal best_score
score = evaluate_subset(subset)
if score > best_score:
best_subset.clear()
best_subset.extend(subset)
best_score = score

def backtrack(subset, idx):


if len(subset) == k:
evaluate_branch(subset)
return
if idx == n:
return
remaining_features = n - idx
if len(subset) + remaining_features >= k:
# Include the current feature in the subset
subset.append(features[idx])
backtrack(subset, idx + 1)
subset.pop()
if len(subset) + remaining_features > k:
# Exclude the current feature from the subset
backtrack(subset, idx + 1)
backtrack([], 0)
return best_subset
# Example usage
if __name__ == '__main__':
# Dummy feature set
features = ['Feature A', 'Feature B', 'Feature C', 'FeatureD', 'Feature E', 'Feature F', 'Feature G',
'Feature H', 'Feature I', 'Feature J']
k = 3 # Number of features to select
selected_features = branch_and_bound(features, k)
print(f"Selected Features: {selected_features}")
Vidhyadhan Commerce college Wadel Road Dhule
Department of Computer Science
Class:- SYBCA SEM -IV Subject BCA 407 Artificial Intelligence
Practical 2. Implementation of informed (Heuristic) search techniques like A* Search
Student Name _____________________________________________________________

def aStarAlgo(start_node, stop_node):

open_set = set(start_node)
closed_set = set()
g = {} #store distance from starting node
parents = {}# parents contains an adjacency map of all nodes

#ditance of starting node from itself is zero


g[start_node] = 0
#start_node is root node i.e it has no parent nodes
#so start_node is set to its own parent node
parents[start_node] = start_node

while len(open_set) > 0:


n = None

#node with lowest f() is found


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):
#nodes 'm' not in first and last set are added to first
#n is set its parent
if m not in open_set and m not in closed_set:
open_set.add(m)
parents[m] = n
g[m] = g[n] + weight

#for each node m,compare its distance from start i.e g(m) to the
#from start through n node
else:
if g[m] > g[n] + weight:
#update g(m)
g[m] = g[n] + weight
#change parent of m to n
parents[m] = n

#if m in closed set,remove and add to open


if m in closed_set:
closed_set.remove(m)
open_set.add(m)

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

# if the current node is the stop_node


# then we begin reconstructin the path from it to the start_node
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

# remove n from the open_list, and add it to closed_list


# because all of his neighbors were inspected
open_set.remove(n)
closed_set.add(n)

print('Path does not exist!')


return None

#define fuction to return neighbor and its distance


#from the passed node
def get_neighbors(v):
if v in Graph_nodes:
return Graph_nodes[v]
else:
return None
#for simplicity we ll consider heuristic distances given
#and this function returns heuristic distance for all nodes
def heuristic(n):
H_dist = {
'A': 11,
'B': 6,
'C': 99,
'D': 1,
'E': 7,
'G': 0,

return H_dist[n]

#Describe your graph here


Graph_nodes = {
'A': [('B', 2), ('E', 3)],
'B': [('C', 1),('G', 9)],
'C': None,
'E': [('D', 6)],
'D': [('G', 1)],

}
aStarAlgo('A', 'G')
Vidhyadhan Commerce college Wadel Road Dhule
Department of Computer Science
Class:- SYBCA SEM -IV Subject BCA 407 Artificial Intelligence
Practical 2. Implementation of informed (Heuristic) search techniques like Hill climbing search
Student Name _____________________________________________________________

def hill_climbing(f, x0):

x = x0 # initial solution

while True:

neighbors = generate_neighbors(x) # generate neighbors of x

# find the neighbor with the highest function value

best_neighbor = max(neighbors, key=f)

if f(best_neighbor) <= f(x): # if the best neighbor is not better than x, stop

return x

x = best_neighbor # otherwise, continue with the best neighbor


Vidhyadhan Commerce college Wadel Road Dhule
Department of Computer Science
Class:- SYBCA SEM -IV Subject BCA 407 Artificial Intelligence
Practical 2. Implementation of informed (Heuristic) search techniques like AO* Search
Student Name _____________________________________________________________

# Cost to find the AND and OR path

def Cost(H, condition, weight = 1):

cost = {}

if 'AND' in condition:

AND_nodes = condition['AND']

Path_A = ' AND '.join(AND_nodes)

PathA = sum(H[node]+weight for node in AND_nodes)

cost[Path_A] = PathA

if 'OR' in condition:

OR_nodes = condition['OR']

Path_B =' OR '.join(OR_nodes)

PathB = min(H[node]+weight for node in OR_nodes)

cost[Path_B] = PathB

return cost

# Update the cost

def update_cost(H, Conditions, weight=1):

Main_nodes = list(Conditions.keys())

Main_nodes.reverse()

least_cost= {}

for key in Main_nodes:

condition = Conditions[key]

print(key,':', Conditions[key],'>>>', Cost(H, condition, weight))

c = Cost(H, condition, weight)

H[key] = min(c.values())

least_cost[key] = Cost(H, condition, weight)

return least_cost

# Print the shortest path

def shortest_path(Start,Updated_cost, H):

Path = Start

if Start in Updated_cost.keys():

Min_cost = min(Updated_cost[Start].values())

key = list(Updated_cost[Start].keys())
values = list(Updated_cost[Start].values())

Index = values.index(Min_cost)

FIND MINIMIMUM PATH KEY

Next = key[Index].split()

# ADD TO PATH FOR OR PATH

if len(Next) == 1:

Start =Next[0]

Path += '<--' +shortest_path(Start, Updated_cost, H)

# ADD TO PATH FOR AND PATH

else:

Path +='<--('+key[Index]+') '

Start = Next[0]

Path += '[' +shortest_path(Start, Updated_cost, H) + ' + '

Start = Next[-1]

Path += shortest_path(Start, Updated_cost, H) + ']'

return Path

H = {'A': -1, 'B': 5, 'C': 2, 'D': 4, 'E': 7, 'F': 9, 'G': 3, 'H': 0, 'I':0, 'J':0}

Conditions = {

'A': {'OR': ['B'], 'AND': ['C', 'D']},

'B': {'OR': ['E', 'F']},

'C': {'OR': ['G'], 'AND': ['H', 'I']},

'D': {'OR': ['J']}

# weight

weight = 1

# Updated cost

print('Updated Cost :')

Updated_cost = update_cost(H, Conditions, weight=1)

print('*'*75)

print('Shortest Path :\n',shortest_path('A', Updated_cost,H))

You might also like