2/20/23, 1:03 AM Ayush AIML Lab
Switch Case for DFS AND BFS
Aim : To enable an option for users to pick options like BFS
and DFS for search
Theory :
BFS, Breadth-First Search, is a vertex-based technique for finding the shortest path in
the graph. It uses a Queue data structure that follows first in first out. In BFS, one
vertex is selected at a time when it is visited and marked then its adjacent are visited
and stored in the queue. It is slower than DFS.
DFS, Depth First Search, is an edge-based technique. It uses the Stack data structure
and performs two stages, first visited vertices are pushed into the stack, and second if
there are no vertices then visited vertices are popped.
In [3]: graph = {
'A': ['Y', 'U', "S"],
'U': ['H', "A"],
'H': ['Y', "K"],
'S': ["K",'L'],
'L': [],
"Y": [],
'H': [],
"K": []
}
def dfsbyAyushKarle(graph, node, visited):
if node not in visited:
visited.append(node)
print(node)
for n in graph[node]:
dfsbyAyushKarle(graph,n, visited)
return visited
def bfsbyAyushKarle(visit_complete, graph, start_node):
visit_complete.append(start_node)
queue = []
queue.append(start_node)
while queue:
s = queue.pop(0)
print(s)
for neighbour in graph[s]:
if neighbour not in visit_complete:
visit_complete.append(neighbour)
queue.append(neighbour)
enter = str(input("Please enter the required case: "))
match enter:
case 'bfs':
bfsbyAyushKarle([], graph, 'A')
case 'dfs':
localhost:8888/lab/tree/Downloads/Ayush AIML Lab.ipynb 1/5
2/20/23, 1:03 AM Ayush AIML Lab
dfsbyAyushKarle(graph,'A', [])
A
Y
U
S
H
K
L
A* Algorithm
Aim : Write a Python code to implement A* Search
Algorithm specifically to solve
3X3- 8 Puzzle problem.
Description: A* search algorithm is an uninformed search algorithm which works on
the concept of heuristic function.
What is A* Algorithm?
A* search algorithm finds the shortest path through the search space using the
heuristic function. In A* algorithm heuristic function f(n) can be denoted as the
combination of g(n)+h(n) where g(n): cost to reach nth node from start node and h(n):
cost to reach destination node from current or nth node.
Code for A* search algorithm:
In [7]: def mov(ar,p,st):
rh=99999
store_st=st.copy()
for i in range(len(ar)):
dupl_st=st.copy()
temp=dupl_st[p]
dupl_st[p]=dupl_st[arr[i]]
dupl_st[arr[i]]=temp
tmp_rh=count(dupl_st)
if tmp_rh<rh:
rh=tmp_rh
store_st=dupl_st.copy()
return store_st,tmp_rh
def print_in_frmt(matrix):
for i in range(9):
if i%3==0 and i>0:
print("")
print(str(matrix[i])+" ", end= " ")
def count(s):
c=0
ideal=[1,2,3,
4,5,6,
7,8,0]
for i in range(9):
if s[i]!=0 and s[i]!=ideal[i]:
localhost:8888/lab/tree/Downloads/Ayush AIML Lab.ipynb 2/5
2/20/23, 1:03 AM Ayush AIML Lab
c=c+1
return c
start=[1,2,3,
0,5,6,
4,7,8]
h=count(start)
level=1
print("\n..................Level" + str(level)+"....................")
print_in_frmt(start)
print("\n Heuristic Value (misplace tiles): " +str(h))
while h>0:
pos=int(start.index(0))
level+=1
if pos==0:
arr=[1,3]
start,h=mov(arr,pos,start)
elif pos==1:
arr=[0,2,4]
start,h=mov(arr,pos,start)
elif pos==2:
arr=[1,5]
start,h=mov(arr,pos,start)
elif pos==3:
arr=[0,4,6]
start,h=mov(arr,pos,start)
elif pos==4:
arr=[1,3,5,7]
start,h=mov(arr,pos,start)
elif pos==5:
arr=[2,4,8]
start,h=mov(arr,pos,start)
elif pos==6:
arr=[3,7]
start,h=mov(arr,pos,start)
elif pos==7:
arr=[4,6,8]
start,h=mov(arr,pos,start)
elif pos==8:
arr=[5,7]
start,h=mov(arr,pos,start)
print("\n...........Level " +str(level)+"...............")
print_in_frmt(start)
print("\nHeuristic value (misplaced tiles): " +str(h))
localhost:8888/lab/tree/Downloads/Ayush AIML Lab.ipynb 3/5
2/20/23, 1:03 AM Ayush AIML Lab
..................Level1....................
1 2 3
0 5 6
4 7 8
Heuristic Value (misplace tiles): 3
...........Level 2...............
1 2 3
4 5 6
0 7 8
Heuristic value (misplaced tiles): 2
...........Level 3...............
1 2 3
4 5 6
7 0 8
Heuristic value (misplaced tiles): 1
...........Level 4...............
1 2 3
4 5 6
7 8 0
Heuristic value (misplaced tiles): 0
Constraint Satisfaction
Aim: Write a Python code to solve some algebraic relations
using constraint satisfaction.
Description: Constraint satisfaction is a technique where a problem is solved when its
values satisfy certain constraints or rules of the problem. Constraint satisfaction
depends on three components, namely:
X: It is a set of variables.
D: It is a set of domains where the variables reside. There is a specific domain for each
variable.
C: It is a set of constraints which are followed by the set of variables.
In constraint satisfaction, domains are the spaces where the variables reside, following the problem
specific constraints. These are the three main elements of a constraint satisfaction technique. The
constraint value consists of a pair of {scope, rel}. The scope is a tuple of variables which participate in
the constraint and rel is a relation which includes a list of values which the variables can take to satisfy
the constraints of the problem.
In [4]: import constraint
from constraint import *
problem=Problem()
problem.addVariable("x",[2,9,8])
problem.addVariable("y",[0,1,2,3,4,5,6,7,8,9])
def my_constraint(x,y):
if x+y>=10:
return True
problem.addConstraint(my_constraint,['x','y'])
s=problem.getSolutions()
for i in s:
print(i)
localhost:8888/lab/tree/Downloads/Ayush AIML Lab.ipynb 4/5
2/20/23, 1:03 AM Ayush AIML Lab
{'x': 8, 'y': 9}
{'x': 8, 'y': 8}
{'x': 8, 'y': 7}
{'x': 8, 'y': 6}
{'x': 8, 'y': 5}
{'x': 8, 'y': 4}
{'x': 8, 'y': 3}
{'x': 8, 'y': 2}
{'x': 9, 'y': 1}
{'x': 9, 'y': 9}
{'x': 9, 'y': 8}
{'x': 9, 'y': 7}
{'x': 9, 'y': 6}
{'x': 9, 'y': 5}
{'x': 9, 'y': 4}
{'x': 9, 'y': 3}
{'x': 9, 'y': 2}
{'x': 2, 'y': 9}
{'x': 2, 'y': 8}
localhost:8888/lab/tree/Downloads/Ayush AIML Lab.ipynb 5/5