0% found this document useful (0 votes)
38 views39 pages

AI Lab

Uploaded by

chennaumadevi42
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)
38 views39 pages

AI Lab

Uploaded by

chennaumadevi42
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/ 39

1)Lists:-

Code:
L=[1,2,3,4]
print(L)
print(L[1])
print(L[1:4])
print(L[-1])
L[2]=5
print(L)
L.append(6)
print(L)
L.insert(6,9)
print(L)
L.extend([1,2,3])
print(L)
delL[2]
print(L)
L.reverse()
print(L)
Output:
[1, 2, 3, 4]
2
[2, 3, 4]
4
[1, 2, 5, 4]
[1, 2, 5, 4, 6]
[1, 2, 5, 4, 6, 9]
[1, 2, 5, 4, 6, 9, 1, 2, 3]
[1, 2, 4, 6, 9, 1, 2, 3]
[3, 2, 1, 9, 6, 4, 2, 1]
2)Tuples:-
Code:
M=( )
print(M)
M=(1,2,3)
print(M)
M=(1,"Hello",3,4)
print(M)
M=("Tech",[8,4,6],1,2,3)
print(M)
print(type(M))
print(M[1])
print(M[-1])
print(M[1:3])
print(M.count('Tech'))
print(M.index(2))
T1=(12,14,143)
T2=(13,17)
T3=(T1+T2)
print(T3)
print(14inT1)
print(12inT1)
print(4 in T1)
print(T1)
del T2
print(T2)
Output:
()
(1,2,3)
(1,'Hello',3,4)
('Tech',[8,4,6],1,2,3)
<class 'tuple'>
[8, 4, 6]
3
([8,4,6], 1)
1
3
(12,14,143,13,17)
True
True
False
(12,14,143)

Name Error Traceback(most recent call last)


Cell In[1], line 24
22 print(T1)
23 delT2
--->24print(T2)

Name Error :name 'T2' is not defined


3)Breadth First Search(BFS):-
Code:
graph={
'5':['3','7'],
'3':['2','4'],
'7':['8'],
'2':[],
'4':['8'],
'8':[]
}
visited=[]
queue=[]

def bfs(visited,graph,node):
visited.append(node)
queue.append(node)
while queue:
m=queue.pop(0)
print(m,end="")
for neighbouringraph[m]:
if neighbor not in visited:
visited.append(neighbour)
queue.append(neighbour)
print("Following is the Breadth-First-Search")
bfs(visited,graph,'5')
Output:
Following is the Breadth-First-Search
537248
4)Depth First Search(DFS):-
Code:
graph={
'5':['3','7'],
'3':['2','4'],
'7':['8'],
'2':[],
'4':['8'],
'8':[]
}
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, '5')
Output:
Following is the Depth-First-Search
5
3
2
4
8
7
5)Travelling Salesman Problem:-
Code:
From sys import max size
from itertools import permutations
v=4
def travelling salesman problem(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
forjini:
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,20,15,55],
[10,0,45,35],
[35,75,0,40],
[30,45,70,0]]
s=0
print(travelling salesman problem(graph, s))
Output:
110
6)Tower of Hanoi problem:-
Code:
Def tower_of_hanoi(disks, source, auxiliary,target):
if disks == 1:
print('Movedisk1fromrod{}torod{}.'.format(source,target)) return
tower_of_hanoi(disks-1,source,target,auxiliary)
print('Movedisk{}fromrod{}torod{}.'.format(disks,source,target))
tower_of_hanoi(disks - 1, auxiliary, source, target)

disks = int(input('Enter the number of disks: '))


tower_of_hanoi(disks,'A','B','C')#Callingthefunction
Output:
Enter the number of disks:3
Move disk1 from rod A to rod C.
Move disk2 from rod A to rod B.
Move disk1 from rod C to rod B.
Move disk3 from rod A to rod C.
Move disk1 from rod B to rod A.
Move disk2 from rod B to rod C.
Move disk1 from rod A to rod C.
7) 8 puzzle problem:-
Code:
Import copy
from heapq import heap push, heap pop

n= 3
row=[1,0,-1,0]
col=[0,-1,0,1]

class PriorityQueue:
def__init__(self):
self.heap = []

def push(self,k):
heappush(self.heap, k)

def pop(self):
return heappop(self.heap)

def empty(self):
return not self.heap

class Node:
def__init__(self, parent, mat, empty_tile_pos, cost, level):
self.parent = parent
self.mat= mat
self.empty_tile_pos = empty_tile_pos
self.cost = cost
self.level=level

deflt(self,nxt):
return self.cost<nxt.cost

def calculateCost(mat,final)->int:
count = 0
for i in range(n):
for j in range(n):
if(mat[i][j]) and (mat[i][j] !=final[i][j]):
count+=1
return count

def newNode(mat,empty_tile_pos,new_empty_tile_pos,level,parent,final)->Node: new_mat =


copy.deepcopy(mat)
x1=empty_tile_pos[0]
y1= empty_tile_pos[1]
x2=new_empty_tile_pos[0]
y2= new_empty_tile_pos[1]
new_mat[x1][y1],new_mat[x2][y2]=new_mat[x2][y2],new_mat[x1][y1]
cost = calculateCost(new_mat, final)
new_node=Node(parent,new_mat,new_empty_tile_pos,cost,level) return
new_node

def printMatrix(mat):
for i in range(n):
for j in range(n):
print("%d"%(mat[i][j]),end="")
print()
def is Safe(x,y):
return x>=0 and x<n and y >=0 and y<n

def print Path(root):


if root == None:
return
printPath(root.parent)
print Matrix(root.mat)
print()

def solve(initial, empty_tile_pos, final):


pq = PriorityQueue()
cost = calculateCost(initial,final)
root=Node (None,initial,empty_tile_pos,cost,0)
pq.push(root)
while not pq.empty():
minimum = pq.pop()
if minimum.cost==0:
printPath(minimum)
return
for i in range(4):
new_tile_pos=[minimum.empty_tile_pos[0]+row[i],minimum.empty_tile_pos[1]+col[i]] if is
Safe(new_tile_pos[0], new_tile_pos[1]):
child=newNode(minimum.mat,minimum.empty_tile_pos,new_tile_pos,minimum.level+1,minimum,
final)
pq.push(child)

initial=[[1,2,3],[5,6,0],[7,8,4]]
final=[[1,2,3],[5,8,6],[0,7,4]]
empty_tile_pos=[1,2]
solve(initial,empty_tile_pos,final)
Output:
1 23
5 60
7 84

1 23
5 06
7 84

1 23
5 86
7 04

1 23
5 86
1 74
8)A*Algorithm:-
Code:
classNode:
"""A node class for A*Pathfinding"""

def__init__(self, parent=None, position=None):


self.parent = parent
self.position=position

self.g=0
self.h=0
self.f=0

def__eq__(self, other):
return self.position == other.position

defastar(maze,start,end):
"""Returns a list of tuples as a path from the given start to the given end in the given maze"""
start_node = Node(None, start)
start_node.g=start_node.h=start_node.f=0
end_node = Node(None, end)
end_node.g=end_node.h=end_node.f=0

open_list = []
closed_list=[]
open_list.append(start_node)

while len(open_list)>0:
#Get the current node
current_node=open_list[0]
current_index = 0
for index, item in enumerate(open_list):
if item.f <current_node.f:
current_node = item
current_index=index

#Pop current off open list, add to closed list


open_list.pop(current_index)
closed_list.append(current_node)

#Found the goal


If current_node==end_node:
path=[]
current=current_node
while current is not None:
path.append(current.position)
current = current.parent
return path[::-1]#Return reversed path

#Generatechildren
children = []
for new_position in [(0, -1), (0, 1), (-1, 0), (1, 0), (-1, -1), (-1, 1), (1, -1), (1, 1)]:# Adjacent squares
node_position=(current_node.position[0]+new_position[0],current_node.position[1]+new_position[1])

#Make sure with in range


if (node_position[0] < 0 or node_position[0] >= len(maze) or
node_position[1]<0ornode_position[1]>=len(maze[0])):
continue

#Make sure walkable terrain


If maze[node_position[0]][node_position[1]]!=0:
continue

#Create new node


new_node=Node(current_node,node_position)

#Append
children.append(new_node)

#Loop through children


for child in children:
#Child is on the closed list
if child in closed_list:
continue

#Create the f,g,and h values


child.g = current_node.g + 1
child.h=((child.position[0]-end_node.position[0])**2)+((child.position[1] -end_node.position[1])**2) child.f
= child.g + child.h

#Child is already in the open list


if child in open_list:
ifchild.g>open_list[open_list.index(child)].g:
continue

#Add the child to the open list


open_list.append(child)

def main():

maze=[[0,0,0,0,1,0,0,0,0,0],
[0,0,0,0,1,0,0,0,0,0],
[0,0,0,0,1,0,0,0,0,0],
[0,0,0,0,1,0,0,0,0,0],
[0,0,0,0,1,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,1,0,0,0,0,0],
[0,0,0,0,1,0,0,0,0,0],
[0,0,0,0,1,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0]]
start=(0,0)
end=(7,6)
path= astar(maze,start,end)
print(path)
if __name =='__main__':
main()
Output:
[(0,0),(1,1),(2,2),(3,3),(4,3),(5,4),(6,5),(7,6)]
9)Hill Climbing Algorithm:-
Code:
Import random

def randomSolution(tsp):
cities=list(range(len(tsp)))
solution = []

for i in range(len(tsp)):
randomCity=cities[random.randint(0,len(cities)-1)]
solution.append(randomCity)
cities.remove(randomCity)

return solution

def routeLength(tsp,solution):
routeLength=0
for i in range(len(solution)):
routeLength + =tsp[solution[i-1]][solution[i]]
return routeLength

def getNeighbours(solution):
neighbours = []
for i in range(len(solution)):
for j in range(i+1,len(solution)):
neighbor = solution.copy()
neighbour[i] = solution[j]
neighbour[j] = solution[i]
neighbours.append(neighbour)
return neighbours

def getBestNeighbour(tsp,neighbours):
bestRouteLength=routeLength(tsp,neighbours[0])
bestNeighbour = neighbours[0]

for neighbor in neighbours:


currentRouteLength=routeLength(tsp,neighbour)
if currentRouteLength < bestRouteLength:
bestRouteLength = currentRouteLength
bestNeighbour = neighbour

return bestNeighbour, bestRouteLength

def hillClimbing(tsp):
currentSolution=randomSolution(tsp)
currentRouteLength=routeLength(tsp,currentSolution)

whileTrue:
neighbours=getNeighbours(currentSolution)
bestNeighbour,bestNeighbourRouteLength=getBestNeighbour(tsp,neighbours) if
bestNeighbourRouteLength < currentRouteLength:
currentSolution=bestNeighbour
currentRouteLength = bestNeighbourRouteLength
else:
break

return currentSolution, currentRouteLength


def main():
tsp = [
[0,400,500,300],
[400,0,300,500],
[500,300,0,400],
[300,500,400, 0]
]

print(hillClimbing(tsp))

if__name=="__main__":
main()
Output:
([3, 2, 1, 0], 1400)
10) Brute force solution to knapsack problem:-
Code:
def knapsack(W, wt, val,n):
if n==0 or W==0:
return 0
if wt[n-1]>W:
return knapsack(W,wt,val,n-1)
else:
return max(
val[n-1]+knapsack(W-wt[n-1],wt,val,n-1),
knapsack(W, wt, val, n-1)
)

val=[10,12,14,16,18,20]
wt=[10,20,30,40,50,]#corrected wt tuple
W =50
n= len(val)
print(knapsack(W, wt, val, n))
Output:
26
11)Chatbot:-
Code:
Import tkinter as tk

def send():
out="you:"+e.get()
text.insert(tk.END,"\n"+out) if
e.get() == 'hi':
text.insert(tk.END, "\n"+" Bot: hello")
elif e.get() == 'hello':
text.insert(tk.END, "\n"+" Bot: hi")
elif e.get() == 'how are you?':
text.insert(tk.END, "\n"+" Bot:i'm fine and you?")
elif e.get() == " i'm fine too":
text.insert(tk.END, "\n"+" Bot: nice to hear that")
else:
text.insert(tk.END, "\n"+" Bot: sorry i didn't get it")

root= tk.Tk()
root.title('IT SOURCE CODE SIMPLE CHATBOT')

text=tk.Text(root,bg='light blue')
text.grid(row=0,column=0,column span=2)

e=tk.Entry(root,width=80)
e.grid(row=1, column=0)

send_button=tk.Button(root,text='send',bg='blue',width=2,command=send)
send_button.grid(row=1, column=1)

root.mainloop()
Output:
12)Annealing algorithm:-
Code:
#convex unimodel optimization function
from numpy import arange
From matplotlib import pyplot

#objective function
def objective(x):
returnx[0]**2.0
#define range forinput
r_min,r_max=-5.0,5.0
#sample input range uniformly at 0.1 increments
inputs=arange(r_min,r_max,0.1)
#compute targets
results=[objective ([x])for x in inputs]
#create a line plot of input vs result
pyplot.plot(inputs,results)
#define optimal input value
x_optima=0.0
#draw a vertical line at the optimal input
pyplot.axvline(x=x_optima,ls='--',color='red')
#show the plot
pyplot.show()
Output:
Code:
#explore temperature vs algorithm iteration for simulated annealing
from matplotlib import pyplot
#total iterations of algorithm
iterations = 100
#initia lalgorithm
initial_temp=10
#array of iterations from 0 to iterations -1
iterations = [i for i in range (iterations)]
#temperatures for each iterations
temperatures=[initial_temp/float(i+1)for i in iterations]
#plot iterations vs temperatures
pyplot.plot(iterations, temperatures)
pyplot.xlabel('Iteration')
pyplot.ylabel('Temperature')
pyplot.show()
Output:
Code:
#explore metropolis acceptance criterion for simulated annealing
from math import exp
Import matplotlib.pyplot as plt

#total iterations of algorithm


iterations = 100
#initial temperature
initial_temp = 10
#array of iterations from 0 to iterations-1
iterations_list=[I for i in range(iterations)]
#temepratures for each iterations
temperatures=[initial_temp/float(i+1)for i in iterations_list]
#mertropolis acceptance criterion

differences=[0.01,0.1,1.0]

for d in differences:
metropolis=[exp(-d/t)for t in temperatures]
#plot iterations vs metropolis
label = 'diff=%.2f' % d
plt.plot(iterations_list, metropolis, label=label)

#inalize plot
plt.xlabel('Iteration')
plt.ylabel('Metropolis Criterion')
plt.legend()
plt.show()
Output:
12)String Occurance:-
Code:
def KMPSearch(pat,txt):
M = len(pat)
N= len(txt)
#create lps[]that will hold the longest prefix suffix values for pattern
lps = [None]*M
j=0 # index for pat[]
#preprocess the pattern(calculate lps[]array)
computeLPSArray(pat, M, lps)

i=0 # index for txt[]


res = 0

while i<N:
if pat[j]==txt[i]:
j=j+1
i= i+1
if j ==M:
#when we find pattern first time,we iterate again to check if there exists more pattern
print(f"Found pattern at index {i - M}")
j = lps[j-1]
res=res+1
#Mismatch after j matches
elif ((i<N)and(pat[j])!= txt[i]):
#Do not match lps[0..lps[j]]characters,they will match any way if(j!=0)
if j != 0:
j=lps[j-1]
else:
i=i+1
return res

def computeLPS Array(pat,M,lps):


#length of the previous longest
# prefix suffix
length=0
i= 1
lps[0]=0#lps[0]isalways0

# the loop calculates lps[i]for


# i=1 to M-1
while i<M:
if pat[i]== pat[length]:
length=length+1
lps[i] = length
i= i+1
else:#(pat[i]!=pat[length])
# this is tricky. consider the example.
# AAACAAAA and i=7.the idea is similar
# to search step.
if length!=0:
length=lps[length- 1]

# also,note that we do not increment


# i here

else:# if(length==0)
lps[i]=length i
=i+1

#driver code
If__name =="__main__":
txt="WELCOME TO PYTJON WORLD PYTHON PYTHON"
pat = "THON"
ans = KMPSearch(pat, txt)
print(f">")
Output:
Found pattern at index 26
Found pattern at index 33
>
14)Higher order functions:-
Code:
def count(arr, x, n):
#get the index of first occurrenceof x
i = first(arr, 0, n-1, x, n)
# if x doesn't exist in arr[]then return-1
if i == -1:
return i
# else get the index of the last occurrence of x.Note that we are only looking in the subarray after first
occurrence
j=last(arr,i,n-1,x,n) #
return count
returnj-i+1

def first(arr,low,high,x,n): if
high >= low:
# low +(high-low)/2
mid=(low+high)//2
if(mid==0 or x>arr[mid-1])and arr[mid]==x: return
mid
elif x>arr[mid]:
return first(arr,(mid+1),high,x,n)
else:
return first(arr, low,(mid-1),x,n)
return -1

def last(arr,low,high,x,n): if
high >= low:
# low+(high-low)/2
mid=(low+high)//2
if(mid==n-1orx<arr[mid+1])and arr[mid]==x: return
mid
elif x<arr[mid]:
return last(arr,low,(mid-1),x,n) else:
return last(arr,(mid+1),high,x,n)
return -1

# driver program to test above functions


arr = [1, 2, 2, 3, 3, 3, 3]
x=3 # element to be counted in arr[]
n = len(arr)
c=count(arr,x,n)
print("% doccurs %d times"%(x, c))
Output:
3 occurs 4 times
15)Wumpusworldproblem:-
Code:
wumpus=[["Save", "Breeze", "PIT", "Breeze"],
["Smell", "Save", "Breeze", "Save"],
["WUMPUS", "GOLD", "PIT", "Breeze"],
["Smell", "Save", "Breeze", "PIT"]]
row=0
column=0
arrow=True
player=True
score=0
while(player):
choice=input("press u to move up\npress d to move down \npress l to move left\npress r to move
right\n") if choice == "u":
if row!=0:
row-=1
else:
print("move denied")

print("current location:",wumpus[row][column],"\n")
elif choice == "d" :
ifrow!=3:
row+=1
else:
print("move denied")

print("current location:",wumpus[row][column],"\n")
elif choice == "l" :
if column!=0:
column-=1
else:
print("move denied")

print("current location:",wumpus[row][column],"\n")
elif choice == "r" :
if column!=3:
column+=1
else:
print("move denied")

print("current location:",wumpus[row][column],"\n")
else:
print("move denied")

if wumpus[row][column]=="Smell" and arrow!=False:


arrow_choice=input("do you want to throw an arrow-->\npress y to throw\npress n to save your arrow\n")
if arrow_choice == "y":
arrow_throw=input("press u to throw up\npress d to throw down\npress l to throw left\npress r to throw
right\n")
if arrow_throw=="u":
if wumpus[row-1][column]=="WUMPUS":
print("wumpus killed!")
score+=1000
print("score:",score)
wumpus[row-
1][column]="Save"wumpus[1][0]=
"Save"
wumpus[3][0]="Save"
else:
print("arrow wasted...")
score-=10
print("score:",score)
elif arrow_throw == "d":
if wumpus[row+1][column]=="WUMPUS":
print("wumpus killed!")
score+=1000
print("score:",score)
wumpus[row+1][column]="Save"wumpus[1][0]="
Save"
wumpus[3][0]="Save"
else:
print("arrow wasted...")
score-=10
print("score:",score)
elif arrow_throw == "l":
if wumpus[row][column-1]=="WUMPUS":
print("wumpus killed!")
score+=1000
print("score:",score)
wumpus[row][column-
1]="Save"wumpus[1][0]="Save"
wumpus[3][0]="Save"
else:
print("arrowwasted...")
score-=10
print("score:",score)
elif arrow_throw == "r":
if wumpus[row][column+1]=="WUMPUS":
print("wumpus killed!")
score+=1000
print("score:",score)
wumpus[row][column+1]="Save"
wumpus[1][0]="Save"
wumpus[3][0]="Save"
else:
print("arrow wasted...")
score-=10
print("score:",score)

arrow=False
if wumpus[row][column]=="WUMPUS":
score-=1000
print("\n Wumpus here!!\n You Die\n And your score is:",score
,"\n")
break
if(wumpus[row][column]=='GOLD'):
score+=1000
print("GOLD FOUND! You won... \n Your score is:",score,"\n")
break
if(wumpus[row][column]=='PIT'):
score-=1000
print("Ahhhhh!!!!\n You fell in p it.\n And your score
is:",score,"\n") break
Output:
press u to move up
press d to movedown
press l to move left
press r to move right

r
current location :Breeze

press u to move up
press d to movedown
press l to move left
press r to move right
d
current location: Save

press u to move up
press d to movedown
press l to move left
press r to move right

d
current location: GOLD

GOLD FOUND! You won....


Your score is:1000

You might also like