AI Lab
AI Lab
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)
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)
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 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
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"""
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
#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])
#Append
children.append(new_node)
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]
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
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
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)
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
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
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")
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