AI Lab Manual Sohail Masood - 2
AI Lab Manual Sohail Masood - 2
Instructor
1. Introduction To Python
Datatype
Programs:
Program 1:
#int
x = 12
y = 23863
print("integer dataype", x)
print("integer dataype", y)
Program 2:
#float
a = 12.432
b = 32.421223
print("float dataype", a)
print("float dataype", b)
Program 3:
#complex
c = 145j
d = 431223412j
print("complex dataype", c)
print("complex dataype", d)
Program 4:
#string
e = 'abdullah'
Program 5:
#List Datatype
list1 = [12,43,"abdullah",'f',12.534,32j]
print("list: ",list1)
#list operations
list1.pop()
list1.append(21.432)
list2 = [23,3,1,5,43,534,12,542]
list2.sort()
list1.clear()
list1.extend(list2)
print("after using extend: ",list1)
Program 6:
#tuple datatype
tuple1 = (12,43,"asdasd")
print(tuple1)
Program 7:
#input
type
print(value1)
type
print(value2)
type
print(value3)
print(value4)
list1.append(value4)
print(list1)
Graded Task:
• Append
• Insert
• Pop
• Sort
• Count
• Sum
• Len
Solution:
list1 = [12,"abdullah",True,12.8,12j]
print(list1)
list1.append(87)
print(list1)
list1.insert(1,67.987)
print(list1)
list2 = [12,34,12,43,54,12,43,34]
print(list2.count(43))
print(sum(list2))
list2.sort(reverse=False)
print(list2)
list3 = ['cat','animal','abdullah']
list3.sort()
print(list3)
listorignial = [12,43,12,54,23]
listcopy = listorignial.copy()
listorignial.append(78)
print(listorignial)
print(listcopy)
list3.extend([12,34.12,43])
print(list3)
print(len(list3))
Lab 2: Condition, Loops, and Functions
Programs:
Program 1:
#c++
#x = 2
#y=3
# if x == 2:
# if y == 4:
# print("abdullah")
# elif x==3:
# print("teacher")
# print("dsasdsda")
# print("dsaads")
# else:
# print("cs-6a")
Program 2:
#loop
#for loop
#for i in range(startrange,cond,inc):
# print(i)
Program 3:
#while loop
#int x=0;
#while(x<10)
#{
# x++;
#}
#while True:
# if value == 1:
# print("abdullah")
# else:
# break
Program 4:
#logical operators
#AND OR NOT
# 0 0 0
# 10 1
# 0 1 1
# 1 1 1
#0 1
# 1 0
#85>=marks<=100
#A grade
#marks = 87
# print("A grade")
Program 5:
#functions
# def func(user):
# return user
# a = func(name)
# print("username: ",a)
# def age(tellage):
# print("age: ",tellage)
# age(aged)
Graded Task:
Solution:
name = input("Enter the name of student: ")
rollno = input("Enter the roll number of student: ")
credit_hour = []
marks = []
grade = []
n = int(input("Enter Number of Courses: "))
for i in range(n):
print("Enter the marks:")
marks = int(input())
if marks >= 85 and marks <= 100:
grade.append(4.00)
elif marks >= 80 and marks <= 84:
grade.append(3.66)
elif marks >= 75 and marks <= 79:
grade.append(3.33)
elif marks >= 71 and marks <= 74:
grade.append(3.00)
elif marks >= 68 and marks <= 70:
grade.append(2.66)
elif marks >= 64 and marks <= 67:
grade.append(2.33)
elif marks >= 61 and marks <= 63:
grade.append(2.00)
elif marks >= 58 and marks <= 60:
grade.append(1.66)
elif marks >= 54 and marks <= 57:
grade.append(1.30)
elif marks >= 50 and marks <= 53:
grade.append(1.00)
else:
grade.append(0.00)
print("Enter the Credit Hours:")
credit_hour.insert(int(i), input())
total_earned = 0
total_ch = 0
for i in range(n):
total_earned = total_earned + (float(grade[i]) *
int(credit_hour[i]))
total_ch = total_ch + int(credit_hour[i])
sgpa = total_earned / total_ch
print("\nName ", name)
print("Roll Number ", rollno)
print("SGPA is ", sgpa)
Lab 3: Classes, Queues, and Stack
Programs:
Program 1:
#stack
stack_data = []
def push():
stack_data.append(user_value)
print("\t",stack_data)
def pop():
if not stack_data:
else:
remove_value = stack_data.pop()
print("\t",stack_data)
def display():
print("\n\tThe values in stack are as follow:")
print("\t",stack_data)
def peak_top():
while True:
if press == 1:
push()
elif press == 2:
pop()
elif press == 3:
display()
elif press == 4:
peak_top()
elif press == 5:
break
else:
Program 2:
#queue
queue_data = []
def push():
queue_data.append(user_value)
print("\t",queue_data)
def pop():
if not queue_data:
else:
remove_value = queue_data.pop(0)
print("\t",queue_data)
def display():
print("\n\tThe values in queue are as follow:")
print("\t",queue_data)
def peak_top():
while True:
if press == 1:
push()
elif press == 2:
pop()
elif press == 3:
display()
elif press == 4:
peak_top()
elif press == 5:
break
else:
Graded Task:
queue_data = []
def push():
queue_data.append(user_value)
print("\t",queue_data)
def pop():
if not queue_data:
remove_value = queue_data.pop(0)
print("\t",queue_data)
def display():
print("\t",queue_data)
while True:
if press == 1:
push()
elif press == 2:
pop()
elif press == 3:
display()
elif press == 4:
break
else:
Programs:
Program 1:
#bfs
tree = {'A':['B','C'],
'B':['D','E'],
'C':['F','G'],
'D':[],
'E':[],
'F':[],
'G':[]}
visted = []
queue = []
queue.append('A')
while queue:
visitedvalue = queue.pop(0)
print(visitedvalue,end=" ")
visted.append(visitedvalue)
for i in tree[visitedvalue]:
if i not in visted:
queue.append(i)
print()
print("bfs",visted)
Program 2:
#dfs
tre = {'A':['B','C'],
'B':['D','E'],
'C':['F','G'],
'D':[],
'E':[],
'F':[],
'G':[]}
stack = []
visited = []
def dfs(visit,tree,node):
stack.append(node)
stack.pop()
visit.append(node)
for i in tree[node]:
dfs(visit,tree,i)
dfs(visited,tre,'A')
Graded Task:
Solution:
tree = {'0':['1','2'],
'1':['3','4'],
'2':['5','6'],
'3':['7'],
'4':['8'],
'5':[],
'6':[],
'7':[],
'8':[]}
visited = []
stack = []
def dfs(visit,dict1,node):
stack.append(node)
print("stack", stack)
temp = stack.pop()
visit.append(temp)
print("visited: ",visit)
for i in dict1[temp]:
dfs(visit,dict1,i)
dfs(visited,tree,'0')
Lab 5: Depth Limited Search, Iterative Deeping Search
Programs:
Program 1:
#dls
tre = {'A':['B','C'],
'B':['D','E'],
'C':['F','G'],
'D':[],
'E':[],
'F':[],
'G':[],
stack = []
visited = []
stack.append(node)
stack.pop()
visit.append(node)
for i in tree[node]:
dls(visit,tree,i,con)
dls(visited,tre,'A',0)
Program 2:
#ids
tre = {'A':['B','C'],
'B':['D','E'],
'C':['F','G'],
'D':['H','I'],
'E':['J','K'],
'F':['L','M'],
'G':['N','O'],
'H':[],
'I':[],
'J':[],
'K':[],
'L':[],
'M':[],
'N':[],
'O':[],
stack = []
visited = []
con += 1
stack.append(node)
stack.pop()
visit.append(node)
for i in tree[node]: #B,C
ids(visit,tree,i,con,ran)
for x in range(1,10):
visited.clear()
stack.clear()
x = x+1
ids(visited,tre,'A',0,x)
print("")
if 'O' in visited:
break
Graded Task:
'B':['D','E'],
'C':['F','G'],
'D':[],
'E':[],
'F':[],
'G':[]}
visited = []
stack = []
def ids(visit,dict1,node,level,levelend):
while level<levelend:
level = level + 1
stack.append(node)
print("stack", stack)
temp = stack.pop()
visit.append(temp)
for i in dict1[temp]:
ids(visit,dict1,i,level,levelend)
for x in range(1,4):
stack.clear()
visited.clear()
print("level - ",x)
ids(visited,tree,'A',0,x)
Datatype
Programs:
Program 1:
#ucs
class Graph:
self.directed = direction
self.graph = defaultdict(list)
self.amount = 0
def edges(self,u,v,wieght):
if self.directed:
value = (wieght,v)
self.graph[u].append(value)
else:
value = (wieght, v)
self.graph[u].append(value)
value = (wieght,u)
self.graph[v].append(value)
visited = []
queue = PriorityQueue()
queue.put((0,currentnode))
item = queue.get()
currentnode = item[1]
self.amount += item[0]
",self.amount,"\n\n")
if currentnode == goalnode:
visited.append(currentnode)
queue.queue.clear()
else:
if currentnode not in visited:
",self.amount)
visited.append(currentnode)
queue.put((child[0],child[1]))
g = Graph(False)
g.graph = defaultdict(list)
g.edges('A','B',2)
g.edges('A','C',3)
g.edges('B','C',4)
g.edges('B','D',1)
g.edges('C','E',2)
g.edges('D','G',4)
g.edges('E','G',7)
print(g.graph)
g.ucs('A','G')
Program 2:
class Tree:
def __init__(self):
self.tree = defaultdict(list)
self.amount = 0
# 'A':[(2,'B'),'C']
def edges(self,u,v,wieght):
value = (wieght,v)
self.tree[u].append(value)
visited = []
queue = []
queue.append((0,currentnode))
print(queue)
#[(0,'A')]
while queue:
check = []
currentnode = item[1]
self.amount += item[0]
if currentnode == goalnode:
visited.append(currentnode)
queue.clear()
else:
",self.amount)
visited.append(currentnode)
check.append((child[0],child[1]))
if not check:
break
else:
item1 = check[0]
item2 = check[1]
if item1[0]<item2[0]:
queue.clear()
queue.append(item1)
del item1
del item2
check.clear()
else:
queue.clear()
queue.append(item2)
del item1
del item2
check.clear()
g = Tree()
g.tree = defaultdict(list)
g.edges('A','B',3)
g.edges('A','C',2)
g.edges('B','D',4)
g.edges('B','E',1)
g.edges('C','F',4)
g.edges('C','G',2)
g.edges('D','H',7)
g.edges('D','I',2)
g.edges('E','J',6)
g.edges('E','K',2)
g.edges('F','L',6)
g.edges('F','M',3)
print(g.tree)
g.hillclimbimg('A','G')
Graded Task:
class Tree:
def __init__(self):
self.tree = defaultdict(list)
self.amount = 0
def edges(self,u,v,wights):
value = (wights,v)
self.tree[u].append(value)
def hillclimb(self,start,goal):
visited = []
queue = []
queue.append((0,start))
while queue:
item = queue.pop(0)
currentnode = item[1]
self.amount += item[0]
if currentnode == goal:
visited.append(currentnode)
print("goal node: ",currentnode," cost: ",self.amount)
break
else:
check = []
if currentnode not in visited:
visited.append(currentnode)
print("path node: ", currentnode, " cost: ", self.amount)
for i in self.tree[currentnode]:
check.append((i[0],i[1]))
if not check:
break
else:
if check[0]<check[1]:
queue.clear()
queue.append(check[1])
check.clear()
else:
queue.clear()
queue.append(check[0])
check.clear()
print("visted: ",visited)
t = Tree()
t.edges('0','1',8)
Lab 7: Local Beam Search, A-star Algorithm
Programs:
Program 1:
class Tree:
def __init__(self):
self.tree = defaultdict(list)
self.amount = 0
self.distance = {}
def edges(self,u,v,wieght):
value = (wieght,v)
self.tree[u].append(value)
def goaldistance(self,node,hd):
self.distance.update({node:hd})
def localbeam(self,cn,g):
visited = []
queue = []
queue.append((0,cn))
while queue:
check = []
item = queue[0]
currentnode = item[1]
self.amount += item[0]
if currentnode == g:
visited.append(cn)
queue.clear()
else:
visited.append(currentnode)
for i in self.tree[currentnode]:
check.append((i[0],i[1]))
print(check)
if not check:
break
else:
item1 = check[0]
item2 = check[1]
if self.distance[item1[1]]<self.distance[item2[1]]:
queue.clear()
queue.append(item1)
del item1
del item2
check.clear()
else:
queue.clear()
queue.append(item2)
del item1
del item2
check.clear()
print("visited: ",visited)
g = Tree()
g.tree = defaultdict(list)
g.edges('A','B',2)
g.edges('A','C',3)
g.edges('B','D',3)
g.edges('B','E',4)
g.edges('C','F',2)
g.edges('C','G',1)
print("tree: ",g.tree)
g.goaldistance('A',42)
g.goaldistance('B',38)
g.goaldistance('C',40)
g.goaldistance('D',12)
g.goaldistance('E',34)
g.goaldistance('F',15)
g.goaldistance('G',0)
g.localbeam('A','G')
Program 2:
#a-star algorithm
closed_set = set()
g = {}
parents = {}
g[start_node] = 0
parents[start_node] = start_node
n = None
for v in open_set:
n=v
pass
else:
open_set.add(m)
parents[m] = n
g[m] = g[n] + weight
else:
parents[m] = n
if m in closed_set:
closed_set.remove(m)
open_set.add(m)
if n == None:
return None
if n == stop_node:
path = []
while parents[n] != n:
path.append(n)
n = parents[n]
path.append(start_node)
path.reverse()
return path
open_set.remove(n)
closed_set.add(n)
return None
def get_neighbors(v):
if v in Graph_nodes:
return Graph_nodes[v]
else:
return None
def heuristic(n):
H_dist = {
'A': 11,
'B': 6,
'C': 99,
'D': 1,
'E': 7,
'G': 0,
return H_dist[n]
Graph_nodes = {
'C': None,
aStarAlgo('A', 'G')
Graded Task:
#A-STAR ALGORITHM:
def aStarAlgo(start_node, stop_node):
open_set = set(start_node)
closed_set = set()
g = {}
parents = {}
g[start_node] = 0
parents[start_node] = start_node
n = None
for v in open_set:
n = v
pass
else:
open_set.add(m)
parents[m] = n
else:
parents[m] = n
if m in closed_set:
closed_set.remove(m)
open_set.add(m)
if n == None:
return None
if n == stop_node:
path = []
while parents[n] != n:
path.append(n)
n = parents[n]
path.append(start_node)
path.reverse()
return path
open_set.remove(n)
closed_set.add(n)
return None
def get_neighbors(v):
if v in Graph_nodes:
return Graph_nodes[v]
else:
return None
def heuristic(n):
H_dist = {
'A': 11,
'B': 6,
'C': 99,
'D': 1,
'E': 7,
'G': 0,
return H_dist[n]
Graph_nodes = {
'C': None,
aStarAlgo('A', 'G')
Lab 8: Min Max Algorithm, Alpha Beta Pruning Algorithm
Programs:
Program 1:
#minmax algorithm
import math
score = []
def minmax(cd,nv,mt,src,td):
if cd == td:
return src[nv]
elif mt:
return max(minmax(cd+1,nv*2,False,src,td),minmax(cd+1,nv*2+1,False,src,td))
else:
return min(minmax(cd+1,nv*2,True,src,td),minmax(cd+1,nv*2+1,True,src,td))
for i in range(ransrc):
score.append(value)
maxterm = True
levels = math.log(ransrc,2)
Program 2:
#alphabeta pruning
import math
maxvalue = 1000
minvalue = -1000
score = []
def alphabeta(cd,nv,mt,src,td,a,b):
if cd == td:
return src[nv]
elif mt:
best = minvalue
for i in range(0,td-1):
v = alphabeta(cd+1,nv*2,False,src,td,a,b)
best = max(best,v)
a = max(a,best)
if b<=a:
break
return best
else:
best = maxvalue
best = max(best, v)
b = max(b, best)
if b <= a:
break
return best
for i in range(ransrc):
score.append(value)
maxterm = True
levels = math.log(ransrc,2)
print("optimal answer:
",alphabeta(currentdepth,nodelevel,maxterm,score,int(levels),maxvalue,minvalue))
Graded Task:
maxvalue = 1000
minvalue = -1000
score = []
def alphabeta(cd,nv,mt,src,td,a,b):
if cd == td:
return src[nv]
elif mt:
best = minvalue
for i in range(0,td-1):
v = alphabeta(cd+1,nv*2,False,src,td,a,b)
best = max(best,v)
a = max(a,best)
if b<=a:
break
return best
else:
best = maxvalue
best = max(best, v)
b = max(b, best)
if b <= a:
break
return best
score.append(value)
maxterm = True
levels = math.log(ransrc,2)
print("optimal answer:
",alphabeta(currentdepth,nodelevel,maxterm,score,int(levels),m
axvalue,minvalue))