0% found this document useful (0 votes)
88 views

AI Lab Manual Sohail Masood - 2

Here is the code for 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) if node not in visited: print("node in stack: ",stack,end=" ") stack.pop() visit.append(node) print("Visited Nodes: ",visit) for i in tree[node]: dfs(visit,tree,i)

Uploaded by

Irum Qayyum
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)
88 views

AI Lab Manual Sohail Masood - 2

Here is the code for 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) if node not in visited: print("node in stack: ",stack,end=" ") stack.pop() visit.append(node) print("Visited Nodes: ",visit) for i in tree[node]: dfs(visit,tree,i)

Uploaded by

Irum Qayyum
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/ 56

Artificial Intelligence Lab Manual

Instructor

Dr. Sohail Masood Bhatti

DEPARTMENT OF COMPUTER SCIENCE


List of Tasks

1. Introduction To Python

2. Condition, Loops, and Functions

3. Classes, Queues, and Stack

4. Depth-First Search, Breadth-First Search

5. Depth Limited Search, Iterative Deeping Search

6. Uniformed Cost Search, Greedy Searching, Hill Climbing Search, Dictionary

Datatype

7. Local Beam Search, A-star Algorithm

8. Min Max Algorithm, Alpha Beta Pruning Algorithm

9. Python Libraries for Machine Learning

10. Data Labelling Tools

11. Training Machine Learning Algorithms

12. Performance Measures of Machine Learning Models

13. Building Machine Learning Applications

14. Deploying Machine Learning Applications


Lab 1: Introduction to Python

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'

f = "my roll is -----"

print("string datatype: ",e)

print("string datatype: ",f)

Program 5:

#List Datatype

#list syntax: list name = [data will be written in large barket]

list1 = [12,43,"abdullah",'f',12.534,32j]

print("list: ",list1)

#list operations

list1.pop()

print("after using pop: ",list1)

list1.append(21.432)

print("after using append",list1)

list2 = [23,3,1,5,43,534,12,542]

list2.sort()

print("after using sort: ",list2)

list1.clear()

print("empty list after using clear: ",list1)

list1.extend(list2)
print("after using extend: ",list1)

Program 6:

#tuple datatype

#tuple syntax: tuple name = (data in these bracket)

tuple1 = (12,43,"asdasd")

print(tuple1)

Program 7:

#input

value1 = input("enter a value: ") #input will be defualt string

type

print(value1)

value2 = float(input("enter a value: ")) #input will be integer

type

print(value2)

value3 = complex(input("enter a value: ")) #input will be integer

type

print(value3)

value4 = int(input("enter a value: ")) #input will be integer type

print(value4)
list1.append(value4)

print(list1)

Graded Task:

Write the code of following operations of list and also add


screenshot of their code:

• 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

#CTRL + / for comment

#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( variable decalre ; conddition ; inc/dec)

#for(int i=10; i>0 ; i--)


#startrange = int(input("enter start range for loop: "))

#cond = int(input("enter the range for loop: "))

#inc = int(input("how much increment: "))

#for i in range(startrange,cond,inc):

# print(i)

Program 3:

#while loop

#int x=0;

#while(x<10)

#{

# x++;

#}

#while True:

# value = int(input("enter 1 if you want to run loop: "))

# if value == 1:

# print("abdullah")

# else:

# break

Program 4:

#logical operators

#AND OR NOT

#C++ AND: &&, OR: ||, NOT: !


#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

#if marks>=85 or marks<=100:

# print("A grade")

Program 5:

#functions

#c++ returntype name()

# name = input("tell username: ")

# def func(user):

# return user

# a = func(name)

# print("username: ",a)

# def age(tellage):
# print("age: ",tellage)

# aged = int(input("tell age:"))

# 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():

user_value = int(input("\n\t* Enter an value: "))

stack_data.append(user_value)

print("\t",stack_data)

def pop():

if not stack_data:

print("\n\tThe list is empty")

else:

remove_value = stack_data.pop()

print("\n\tThe last value from the stack is removed")

print("\tThe value removed from stack: ", remove_value)

print("\t",stack_data)

def display():
print("\n\tThe values in stack are as follow:")

print("\t",stack_data)

def peak_top():

print("\n\tThe top value in the stack: ", stack_data[-1])

while True:

print("\n\t* Press 1: To enter value in stack")

print("\n\t* Press 2: To remove value in stack")

print("\n\t* Press 3: To display values in stack")

print("\n\t* Press 4: To display top value in stack")

print("\n\t* Press 5: To quit from stack progran")

press = int(input("Press a key: "))

if press == 1:

push()

elif press == 2:

pop()

elif press == 3:

display()

elif press == 4:

peak_top()

elif press == 5:
break

else:

print("\n\t* Wrong key press*")

Program 2:

#queue

queue_data = []

def push():

user_value = int(input("\n\t* Enter an value: "))

queue_data.append(user_value)

print("\t",queue_data)

def pop():

if not queue_data:

print("\n\tThe list is empty")

else:

remove_value = queue_data.pop(0)

print("\n\tThe starting value from the queue is removed")

print("\tThe values removed from queue: ", remove_value)

print("\t",queue_data)

def display():
print("\n\tThe values in queue are as follow:")

print("\t",queue_data)

def peak_top():

print("\n\tThe top value in the queue: ", queue_data[-1])

while True:

print("\n\t* Press 1: To enter value in queue")

print("\n\t* Press 2: To remove value in queue")

print("\n\t* Press 3: To display values in queue")

print("\n\t* Press 4: To display top value in queue")

print("\n\t* Press 5: To quit from queue progran")

press = int(input("Press a key: "))

if press == 1:

push()

elif press == 2:

pop()

elif press == 3:

display()

elif press == 4:

peak_top()

elif press == 5:
break

else:

print("\n\t* Wrong key press*")

Graded Task:

Write the code of queue?


Solution:

queue_data = []

def push():

user_value = int(input("\n\t* Enter an value: "))

queue_data.append(user_value)

print("\t",queue_data)

def pop():

if not queue_data:

print("\n\tThe list is empty")


else:

remove_value = queue_data.pop(0)

print("\n\tThe starting value from the queue is


removed")

print("\tThe values removed from queue: ",


remove_value)

print("\t",queue_data)

def display():

print("\n\tThe values in queue are as follow:")

print("\t",queue_data)

while True:

print("\n\t* Press 1: To enter value in queue")


print("\n\t* Press 2: To remove value in queue")

print("\n\t* Press 3: To display values in queue")

print("\n\t* Press 4: To quit from queue progran")

press = int(input("Press a key: "))

if press == 1:

push()

elif press == 2:

pop()

elif press == 3:

display()

elif press == 4:

break

else:

print("\n\t* Wrong key press*")


Lab 4: Depth-First Search, Breadth-First Search

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:

print("Data in queue: ",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)

if node not in visited:


print("node in stack: ",stack,end=" ")

stack.pop()

visit.append(node)

print("Visited Nodes: ",visit)

for i in tree[node]:

dfs(visit,tree,i)

dfs(visited,tre,'A')

Graded Task:

Write the code of Depth First Search?

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)

if node not in visit:

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 = []

def dls(visit, tree, node, con):

while con < 2:


con += 1

stack.append(node)

if node not in visited:

print("node in stack: ",stack,end=" ")

stack.pop()

visit.append(node)

print("Visited Nodes: ",visit)

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 = []

def ids(visit, tree, node, con, ran):

while con < ran:

con += 1

if node not in visited:

stack.append(node)

print("\t\tstack: ", stack)

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

print("LEVEL - ", x, " :")

ids(visited,tre,'A',0,x)

print("visted: ", visited)

print("")

if 'O' in visited:

break

Graded Task:

Write the code of Iterative Deeping Search?


Solution:
tree = {'A':['B','C'],

'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

if node not in visit:

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)

print("visited: ", visited)


Lab 6: Uniformed Cost Search, Greedy Searching, Hill Climbing Search, Dictionary

Datatype

Programs:

Program 1:

#ucs

from _collections import defaultdict

from queue import PriorityQueue

class Graph:

def __init__(self, direction):

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)

def ucs(self, currentnode, goalnode):

visited = []

queue = PriorityQueue()

queue.put((0,currentnode))

while not queue.empty():

item = queue.get()

currentnode = item[1]

self.amount += item[0]

print("current node path: ",currentnode," - amount:

",self.amount,"\n\n")

if currentnode == goalnode:

print("goal node: ",currentnode," - total amount: ",self.amount)

visited.append(currentnode)

queue.queue.clear()

else:
if currentnode not in visited:

print("path node: ",currentnode," - amount to this node:

",self.amount)

visited.append(currentnode)

for child in self.graph[currentnode]:

queue.put((child[0],child[1]))

print("\n\nvisted value: ",visited)

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:

#hill climbing search

from _collections import defaultdict

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)

def hillclimbimg(self, currentnode, goalnode):

visited = []

queue = []

queue.append((0,currentnode))

print(queue)

#[(0,'A')]

while queue:
check = []

item = queue[0] #(0,'A')

currentnode = item[1]

self.amount += item[0]

if currentnode == goalnode:

print("goal node: ",currentnode," - total amount: ",self.amount)

visited.append(currentnode)

queue.clear()

else:

if currentnode not in visited:

print("path node: ",currentnode," - amount to this node:

",self.amount)

visited.append(currentnode)

for child in self.tree[currentnode]:

check.append((child[0],child[1]))

print("values: ",check) #[(2,B),(3,C)

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()

print("\n\nvisted value: ",visited)

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:

Write the code of Hill Climbing Algorithm?


Solution:
from _collections import defaultdict

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:

#local beam search

from _collections import defaultdict

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:

print("goal node: ",currentnode," amount: ",self.amount)

visited.append(cn)

queue.clear()

else:

if currentnode not in visited:

print("current node: ",currentnode," amount: ",self.amount)

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)

print("hue distance from goal node: ",g.distance)

g.localbeam('A','G')

Program 2:

#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

while len(open_set) > 0:

n = None

for v in open_set:

if n == None or g[v] + heuristic(v) < g[n] + heuristic(n):

n=v

if n == stop_node or Graph_nodes[n] == None:

pass

else:

for (m, weight) in get_neighbors(n):

if m not in open_set and m not in closed_set:

open_set.add(m)

parents[m] = n
g[m] = g[n] + weight

else:

if g[m] > g[n] + weight:

g[m] = g[n] + weight

parents[m] = n

if m in closed_set:

closed_set.remove(m)

open_set.add(m)

if n == None:

print('Path does not exist!')

return None

if n == stop_node:

path = []

while parents[n] != n:

path.append(n)
n = parents[n]

path.append(start_node)

path.reverse()

print('Path found: {}'.format(path))

return path

open_set.remove(n)

closed_set.add(n)

print('Path does not exist!')

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 = {

'A': [('B', 2), ('E', 3)],

'B': [('C', 1), ('G', 9)],

'C': None,

'E': [('D', 6)],

'D': [('G', 1)],

aStarAlgo('A', 'G')

Graded Task:

Write code of A-star and add screenshot of output?


Solution:

#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

while len(open_set) > 0:

n = None

for v in open_set:

if n == None or g[v] + heuristic(v) < g[n] + heuristic(n):

n = v

if n == stop_node or Graph_nodes[n] == None:

pass

else:

for (m, weight) in get_neighbors(n):

if m not in open_set and m not in closed_set:

open_set.add(m)
parents[m] = n

g[m] = g[n] + weight

else:

if g[m] > g[n] + weight:

g[m] = g[n] + weight

parents[m] = n

if m in closed_set:

closed_set.remove(m)

open_set.add(m)

if n == None:

print('Path does not exist!')

return None

if n == stop_node:

path = []

while parents[n] != n:

path.append(n)

n = parents[n]
path.append(start_node)

path.reverse()

print('Path found: {}'.format(path))

return path

open_set.remove(n)

closed_set.add(n)

print('Path does not exist!')

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 = {

'A': [('B', 2), ('E', 3)],

'B': [('C', 1), ('G', 9)],

'C': None,

'E': [('D', 6)],

'D': [('G', 1)],

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))

ransrc = int(input("enter the range of terminal: "))

for i in range(ransrc):

value = int(input("enter terminal value at index "+str(i)+" : "))

score.append(value)

print("terminal values: ",score)

maxterm = True

currentdepth = int(input("enter current depth: "))

levels = math.log(ransrc,2)

print("levels of tree: ",levels)


nodelevel = int(input("enter node level: "))

print("optimal answer: ",minmax(currentdepth,nodelevel,maxterm,score,levels))

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

for i in range(0, td - 1):


v = alphabeta(cd + 1, nv * 2, True, src, td, a, b)

best = max(best, v)

b = max(b, best)

if b <= a:

break

return best

ransrc = int(input("enter the range of terminal: "))

for i in range(ransrc):

value = int(input("enter terminal value at index "+str(i)+" : "))

score.append(value)

print("terminal values: ",score)

maxterm = True

currentdepth = int(input("enter current depth: "))

levels = math.log(ransrc,2)

print("levels of tree: ",levels)

nodelevel = int(input("enter node level: "))

print("optimal answer:

",alphabeta(currentdepth,nodelevel,maxterm,score,int(levels),maxvalue,minvalue))

Graded Task:

Write code of Alpha Beta Pruning?


Solution:
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

for i in range(0, td - 1):

v = alphabeta(cd + 1, nv * 2, True, src, td, a, b)

best = max(best, v)

b = max(b, best)

if b <= a:

break

return best

ransrc = int(input("enter the range of terminal: "))


for i in range(ransrc):

value = int(input("enter terminal value at index


"+str(i)+" : "))

score.append(value)

print("terminal values: ",score)

maxterm = True

currentdepth = int(input("enter current depth: "))

levels = math.log(ransrc,2)

print("levels of tree: ",levels)

nodelevel = int(input("enter node level: "))

print("optimal answer:
",alphabeta(currentdepth,nodelevel,maxterm,score,int(levels),m
axvalue,minvalue))

You might also like