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)
del L[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(14 in T1)
print(12 in T1)
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)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[1], line 24
22 print(T1)
23 del T2
---> 24 print(T2)
def bfs(visited,graph,node):
visited.append(node)
queue.append(node)
while queue:
m=queue.pop(0)
print(m,end="")
for neighbour in graph[m]:
if neighbour 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 maxsize
from itertools import permutations
v=4
def travellingsalesmanproblem(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,20,15,55],
[10,0,45,35],
[35,75,0,40],
[30,45,70,0]]
s=0
print(travellingsalesmanproblem(graph,s))
Output:
110
6)Tower of Hanoi problem:-
Code:
def tower_of_hanoi(disks, source, auxiliary, target):
if disks == 1:
print('Move disk 1 from rod {} to rod {}.'.format(source,target))
return
tower_of_hanoi(disks - 1, source, target, auxiliary)
print('Move disk {} from rod {} to rod {}.'.format(disks,source,target))
tower_of_hanoi(disks - 1, auxiliary, source, target)
Output:
Enter the number of disks: 3
Move disk 1 from rod A to rod C.
Move disk 2 from rod A to rod B.
Move disk 1 from rod C to rod B.
Move disk 3 from rod A to rod C.
Move disk 1 from rod B to rod A.
Move disk 2 from rod B to rod C.
Move disk 1 from rod A to rod C.
7)8 puzzle problem:-
Code:
import copy
from heapq import heappush, heappop
n=3
row = [1, 0, -1, 0]
col = [0, -1, 0, 1]
class PriorityQueue:
def __init__(self):
self.heap = []
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
def printMatrix(mat):
for i in range(n):
for j in range(n):
print("%d" % (mat[i][j]), end=" ")
print()
def isSafe(x, y):
return x >= 0 and x < n and y >= 0 and y < n
def printPath(root):
if root == None:
return
printPath(root.parent)
printMatrix(root.mat)
print()
Output:
123
560
784
123
506
784
123
586
704
123
586
074
8)A* Algorithm:-
Code:
class Node:
"""A node class for A* Pathfinding"""
self.g = 0
self.h = 0
self.f = 0
open_list = []
closed_list = []
open_list.append(start_node)
# Generate children
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 getNeighbours(solution):
neighbours = []
for i in range(len(solution)):
for j in range(i+1, len(solution)):
neighbour = solution.copy()
neighbour[i] = solution[j]
neighbour[j] = solution[i]
neighbours.append(neighbour)
return neighbours
def hillClimbing(tsp):
currentSolution = randomSolution(tsp)
currentRouteLength = routeLength(tsp, currentSolution)
while True:
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)
)
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')
e = tk.Entry(root, width=80)
e.grid(row=1, column=0)
root.mainloop()
Output:
12)Annealing algorithm:-
Code:
#convex unimodel optimization function
from numpy import arange
from matplotlib import pyplot
#objective function
def objective(x):
return x[0]**2.0
#define range for input
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
#initial algorithm
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
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:
13)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 anyway 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 occurrence of 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
return j-i+1
Output:
3 occurs 4 times
15)Wumpus world problem:-
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")
arrow=False
if wumpus[row][column] == "WUMPUS" :
score-=1000
print("\nWumpus here!!\n You Die\nAnd your score is: ",score
,"\n")
break
if(wumpus[row][column]=='GOLD'):
score+=1000
print("GOLD FOUND!You won....\nYour score is: ",score,"\n")
break
if(wumpus[row][column]=='PIT'):
score-=1000
print("Ahhhhh!!!!\nYou fell in pit.\nAnd your score is: ",score,"\n")
break
Output:
press u to move up
press d to move down
press l to move left
press r to move right
r
current location: Breeze
press u to move up
press d to move down
press l to move left
press r to move right
d
current location: Save
press u to move up
press d to move down
press l to move left
press r to move right
d
current location: GOLD