|
|
(AUTONOMOUS) An ISO 9001:2015 and
ISO 14001:2015 Certified Institution Affiliated to Anna
University, Chennai, Approved by AICTE, New Delhi & Recognized by UGC with
2(f) & 12(B), Re-accredited by NAAC with “A+” NBA Accredited UG
Courses: ECE | EEE | MECH | MCT Nehru Gardens, T. M. Palayam, Coimbatore -
641 105. |
|

U23AD305 – Artificial Intelligence – I
Laboratory
Regulation: 2023 Revised
Name:
__________________________________________
Reg No.:
________________________________________
Sem / Year:
______________________________________
VISION
To
emerge as a Centre of Excellence in Artificial Intelligence and Data Science Technologies and Tools to produce Industry
Ready Artificial Intelligence Engineers and Data Scientists to serve
the nation and to meet the
Industry Challenges
MISSION
• To impart quality
education by creative
students-centric teaching learning
processes
•
To groom students technologically superior and ethically stronger and responsible throughout the professional career
• To equip students
with interdisciplinary skill sets and leadership qualities
to cater the needs of the industries and society
|
NEHRU INSTITUTE OF
ENGINEERING AND TECHNOLOGY |
||
|
|
(AUTONOMOUS) An
ISO 9001:2015 and ISO 14001:2015 Certified Institution Affiliated
to Anna University, Chennai, Approved by AICTE, New Delhi & Recognized
by UGC with 2(f) & 12(B), Re-accredited by NAAC with “A+” NBA
Accredited UG Courses: ECE | EEE | MECH
| MCT Nehru Gardens,
T. M. Palayam, Coimbatore - 641 105. |
|

Certified that this is Bonafide record of
work done in U23AD305 ARTIFICIAL INTELLIGENCE – I LABORATORY by
Mr./Ms._________________________________________________________ Reg.No.
___________________________________ of this institution as prescribed by
regulation 2023 revised, for the III semester course in Artificial Intelligence
and Data Science branch during the academic year 2025-2026(ODD).
Date : HOD
Submitted for the Autonomous practical examination held on at Nehru Institute
of Engineering and Technology, Coimbatore
– 105
![]()
……………………………………. ……………………………. Internal Examiner External Examiner
LIST OF EXPERIMENTS
|
S.No. |
Date |
Name of the Experiment |
Page No |
Marks |
Signature |
|
1. |
|
Implement 8 Puzzle problem
using Python |
|
|
|
|
1.2. |
|
Implement N queen Problem using Python |
|
|
|
|
1.3. |
|
Implement Crypt arithmetic problem using Python |
|
|
|
|
2 |
|
Implement A* search algorithm using Python |
|
|
|
|
3 |
|
Implement Minimax algorithm using Python |
|
|
|
|
4. |
|
Implement Map Coloring using
Python |
|
|
|
|
5. |
|
Implement Propositional Model checking
algorithm using Cluegame |
|
|
|
|
6.1. |
|
Implement Breadth first search using
Python |
|
|
|
|
6.2 |
|
Implement Depth
first search using
Python |
|
|
|
|
7 |
|
Implement Build Naïve
Bayes Model Using Python |
|
|
|
|
8 |
|
Implement Bayesian Network
and Perform Inference in
Python |
|
|
|
|
|
|
Mini-Project |
|
|
|
VISION
To
emerge as a Centre of Excellence in Artificial Intelligence and Data Science
Technologies and Tools to produce
Industry Ready Artificial Intelligence Engineers
and Data Scientists to serve the nation and to meet the Industry Challenges
MISSION
• To impart quality
education by creative
students-centric teaching learning
processes
• To groom students technologically superior
and ethically stronger
and responsible throughout the professional career
• To equip students
with interdisciplinary skill
sets and leadership qualities
to cater the needs
of the industries and society

Aim:
Write a program to implement 8-Puzzle
problem using Python.
Algorithm:
Step 1: Start a program
Step 2: Declare the variables.
Step 3: Get the values using input
function. Step 4: Then calculate the
approximate value.
Step 5: print the result of program using
print function
Step 6: Stop the program execution.
Program:
class Solution:
def solve(self, board):
dict = {} flatten
= []
for i in range(len(board)): flatten
+= board[i] flatten
= tuple(flatten) dict[flatten]
= 0
if flatten
== (0, 1, 2, 3, 4, 5,
6, 7, 8):
return 0
return self.get_paths(dict)
def get_paths(self, dict):
cnt = 0 while True:
current_nodes = [x for x in dict if dict[x]
== cnt]if len(current_nodes) == 0:
return -1
for node in current_nodes:
next_moves = self.find_next(node)for move in
next_moves:
if move not in dict:
dict[move] = cnt + 1
if move == (0, 1, 2,
3, 4, 5, 6, 7, 8):
return cnt + 1
cnt += 1 def
find_next(self, node):
moves = { 0: [1, 3],
1: [0, 2, 4],
2: [1, 5],
3: [0, 4, 6],
4: [1, 3, 5, 7],
5: [2, 4, 8],
6: [3, 7],
7: [4, 6, 8],
8: [5, 7],
}
results = []
pos_0 = node.index(0) for move in
moves[pos_0]:
new_node = list(node)
new_node[move], new_node[pos_0] = new_node[pos_0], new_node[move] results.append(tuple(new_node))
return results
ob = Solution(
)matrix = [
[3, 1, 2],
[4, 7, 5],
[6, 8, 0]
]
print("NO OF MOVES==",ob.solve(matrix))
OUTPUT:
NO OF MOVES== 4
Result :
Thus the program to implement 8-Puzzle
problem is executed
and the output is obtained.

Aim:
Write a program to implement N-Queens
problem using Python.
Algorithm:
Step 1: Start a program
Step 2: Declare the variables.
Step
3: Get the values using input function. Step
4: Then calculate the approximate value.
Step 5: print the result of program using print function
Step 6: Stop the program execution.
Program:
# Problem using backtracking
global N N = 4
def printSolution(board): for i in range(N):
for j in range(N): print
board[i][j], print
def isSafe(board, row, col):
if board[row][i] == 1: return
False
for i, j in zip(range(row,
-1, -1), range(col, -1, -1)): if board[i][j] == 1:
return False
for i, j in zip(range(row, N, 1), range(col, -1, -1)): if board[i][j] == 1:
return False return True
def solveNQUtil(board, col):
if col >= N: return
True for i in range(N):
if isSafe(board, i, col):
if solveNQUtil(board, col + 1) == True: return True
board[i][col] = 0 def solveNQ():
board = [ [0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]
]
if solveNQUtil(board, 0) == False:
print "Solution does not exist" return
False printSolution(board) return True
Output:
0 0 1 0
1 0 0 0
0 0 0 1
0 1 0 0
Result :
Thus the program to implement N-Queens problem is executed and the output
is obtained.

Aim:
Write a program to implement CryptArithmetic problem using Python.
Algorithm:
Step 1: Start a program
Step 2: Declare the variables.
Step
3: Get the values using input function. Step
4: Then calculate the approximate value.
Step 5: print the result of program using print function
Step 6: Stop the program execution.
Program:
# Function
to check if the
# assignment of digits to # characters is possible
def isSolvable(words, result): # Stores the value
# assigned to alphabets
mp = [-1]*(26)
# Stores if a number
# is assigned to any # character or not used = [0]*(10)
# Stores the sum of position # value of a character
# in every string
Hash = [0]*(26)
# Stores if a character # is at index 0 of any # string
CharAtfront = [0]*(26)
# Stores the string formed # by concatenating every # occurred character only # once
uniq = ""
# Iterator over the array, # words
for word in range(len(words)):
# Iterate over the string, # word
for i in range(len(words[word])):
# Stores the character
# at ith position
ch = words[word][i] # Update Hash[ch-'A]
Hash[ord(ch) - ord('A')] += pow(10, len(words[word]) - i - 1)
# If mp[ch-'A'] is -1
if mp[ord(ch) - ord('A')] == -1:
mp[ord(ch) - ord('A')]
= 0 uniq += str(ch)
# If i is 0 and word
# length is greater # than 1
if i == 0 and len(words[word]) > 1:
CharAtfront[ord(ch) - ord('A')] = 1
# Iterate over the string
result
for i in range(len(result)):
ch = result[i]
Hash[ord(ch) - ord('A')] -= pow(10, len(result) - i - 1)
# If mp[ch-'A] is -1
if mp[ord(ch) - ord('A')] == -1:
mp[ord(ch) - ord('A')] = 0
uniq += str(ch)
# If i is 0 and length of # result is greater than 1
if i ==
0 and len(result) > 1:
CharAtfront[ord(ch) - ord('A')] = 1
mp = [-1]*(26)
# Recursive call of the function
return True
# Auxiliary Recursive
function # to perform backtracking
def solve(words, i, S, mp, used, Hash, CharAtfront):
# If i is word.length
if i == len(words):
# Return true if S is 0 return S == 0
# Stores the character at # index i
ch = words[i]
# Stores the mapped value # of ch
val = mp[ord(words[i]) - ord('A')] # If val
is -1
if val != -1:
# Recursion
return solve(words, i + 1, S + val * Hash[ord(ch) - ord('A')], mp, used, Hash,
CharAtfront)
# Stores if there is any
# possible solution
x = False
# Iterate over the range for l in range(10):
# If CharAtfront[ch-'A'] # is true and l is 0
if CharAtfront[ord(ch) - ord('A')] == 1 and l == 0:
continue
# If used[l]
is true if used[l] == 1:
continue # Assign l to ch
mp[ord(ch) - ord('A')] = l
# Marked l as used used[l] = 1
# Recursive function
call
x |= solve(words, i + 1, S + l * Hash[ord(ch) - ord('A')], mp,
used, Hash, CharAtfront) # Backtrack
mp[ord(ch) - ord('A')]
= -1 # Unset used[l]
used[l] = 0
# Return the value of x; return x
arr = [ "SIX", "SEVEN", "SEVEN" ] S = "TWENTY"
# Function
Call
if isSolvable(arr, S): print("Yes")
else:
print("No")
Output :
Yes
Result :
Thus the program
to implement CryptArithmetic problem
is executed and the output is obtained.

Aim:
Write a program to implement A* Search algorithm
using Python.
Algorithm:
Step 1: Start a program
Step 2: Declare the variables.
Step
3: Get the values using input function. Step
4: Then calculate the approximate value.
Step 5: print the result of program using print function
Step 6: Stop the program execution.
Program:
from collections import deque
class Graph:
# example of adjacency list (or rather map) # adjacency_list = {
# 'A': [('B',
1), ('C', 3), ('D', 7)], # 'B': [('D', 5)],
# 'C': [('D', 12)]
# }
def init (self, adjacency_list):
self.adjacency_list = adjacency_list def get_neighbors(self, v):
return self.adjacency_list[v]
# heuristic function
with equal values
for all nodes def h(self, n):
H = { 'A': 1,
'B': 1,
'C': 1,
'D': 1
}
return H[n]
def a_star_algorithm(self, start_node, stop_node):
# open_list is a list of nodes
which have been visited, but who's neighbors # haven't all been inspected,
starts off with the start node
# closed_list is a list of nodes which have been visited # and who's neighbors have been
inspected
open_list = set([start_node]) closed_list = set([])
# g contains
current distances from start_node to all other nodes # the default value (if it's
not found in the map) is +infinity
g = {}
g[start_node] = 0
# parents contains
an adjacency map of all nodes
parents = {}
parents[start_node] = start_node while len(open_list) > 0:
n = None
# find a node
with the lowest
value of f() - evaluation function for v in open_list:
if n == None or g[v] + self.h(v) < g[n] + self.h(n):
n = v;
if n == None:
print('Path does not exist!')
return None
# if the current node is the stop_node
# then we begin reconstructin the path from it
to the start_node if n == stop_node:
reconst_path = [] while
parents[n] != n: reconst_path.append(n) n
= parents[n]
reconst_path.append(start_node)
reconst_path.reverse()
print('Path found: {}'.format(reconst_path)) return
reconst_path
# for all neighbors of the current
node do for (m, weight) in self.get_neighbors(n):
# if the current node isn't in both open_list and closed_list # add
it to open_list and note n as it's parent
if m not in open_list
and m not in closed_list: open_list.add(m)
parents[m] =
n
g[m] = g[n] + weight
# otherwise, check if it's quicker to first visit
n, then m # and if it is, update parent data and g data
# and if the node was in the closed_list, move it to open_list else:
if g[m] > g[n] + weight:
g[m] = g[n] + weight parents[m] = n
if m in closed_list: closed_list.remove(m)
open_list.add(m)
# remove n from the open_list,
and add it to closed_list # because all of his neighbors
were inspected open_list.remove(n)
closed_list.add(n) print('Path does not exist!')
return None
Output:
Path found: ['A',
'B', 'D']
['A', 'B', 'D']
Result :
Thus the program to implement A* Search algorithm is executed and the output is obtained.

Aim:
Write a program to implement MINMAX algorithm using
Python.
Algorithm:
Step 1: Start a program
Step 2: Declare the variables.
Step
3: Get the values using input function. Step
4: Then calculate the approximate value.
Step 5: print the result of program using print function
Step 6: Stop the program execution.
Program:
class TreeNode:
def init (self, data,
left = None, right = None):
self.val = data
self.left = left self.right = right
class Solution:
def helper(self, root,
h, currentHeight):
if not root:
return
self.helper(root.left,
h, currentHeight + 1) self.helper(root.right,
h, currentHeight + 1)
if currentHeight < h:
if currentHeight % 2 == 0:
if root.left
and root.right:
root.val = max(root.left.val, root.right.val) elif root.left:
root.val = root.left.val elif root.right:
root.val = root.right.val else:
if root.left and root.right:
root.val = min(root.left.val, root.right.val) elif root.left:
root.val = root.left.val elif root.right:
root.val = root.right.val def height(self, root):
if not root:
return 0
return 1 + max(self.height(root.left), self.height(root.right)) def solve(self,
root):
h =
self.height(root)
self.helper(root, h, 0) return root
def print_tree(root):
if root is not None:
print_tree(root.left) print(root.val, end = ', ')
print_tree(root.right) ob = Solution()
root =
TreeNode(0) root.left = TreeNode(3) root.right = TreeNode(0)
root.right.left
= TreeNode(0) root.right.right = TreeNode(0) root.right.left.left =
TreeNode(-3) root.right.right.right = TreeNode(4) print_tree(ob.solve(root))
Input :
root =
TreeNode(0) root.left = TreeNode(3) root.right
= TreeNode(0)
root.right.left
= TreeNode(0) root.right.right = TreeNode(0) root.right.left.left =
TreeNode(-3) root.right.right.right = TreeNode(4)
Output :
3, 3, -3, -3, -3, 4, 4,
Result :
Thus the program to implement MINMAX algorithm is executed and the output is obtained.

Aim:
Write a program to implement Map Colouring algorithm using Python.
Algorithm:
Step 1: Start a program
Step 2: Declare the variables.
Step
3: Get the values using input function. Step
4: Then calculate the approximate value.
Step 5: print the result of program using print function
Step 6: Stop the program execution.
Program:
colors = ['Red',
'Blue', 'Green'] states = ['wa',
'nt', 'sa', 'q', 'nsw', 'v'] neighbors = {}
neighbors['wa'] = ['nt', 'sa']
neighbors['nt']
= ['wa', 'sa', 'q'] neighbors['sa'] = ['wa',
'nt', 'q', 'nsw',
'v'] neighbors['q'] = ['nt', 'sa', 'snw']
neighbors['nsw'] = ['q', 'sa', 'v']
neighbors['v'] = ['sa', 'nsw'] colors_of_states = {}
def promising(state, color):
for neighbor in neighbors.get(state): color_of_neighbor = colors_of_states.get(neighbor)
if color_of_neighbor == color:
return False
return True
def get_color_for_state(state):
for color in colors:
if promising(state, color): return color
def main():
for state in states:
colors_of_states[state] =
get_color_for_state(state) print(colors_of_states)
main()
Output :
{'wa': 'Red',
'nt': 'Blue', 'sa': 'Green', 'q': 'Red', 'nsw':
'Blue', 'v': 'Red'}
Result :
Thus the program
to implement Map Colouring algorithm is executed
and the output is obtained.
![]()
Aim:
Write a program to implement propositional model checking algorithm using Python.
Algorithm:
Step 1: Start a program
Step 2: Declare the variables.
Step
3: Get the values using input function. Step
4: Then calculate the approximate value.
Step 5: print the result of program using print function
Step 6: Stop the program execution.
Program:
import random
# library that we use in order to choose # on random words from a list of words
name = input("What is your name? ")
# Here the user
is asked to enter the name first
print("Good Luck ! ", name)
words = ['rainbow', 'computer', 'science', 'programming', 'python', 'mathematics', 'player', 'condition',
'reverse', 'water', 'board', 'geeks']
# Function
will choose one random
# word from this list of words word =
random.choice(words) print("Guess the characters") guesses = ''
# any number
of turns can be used here
turns = 12
while turns
> 0:
# counts the number of times a user fails failed = 0
# all characters from the input # word taking one at a time. for
char in word:
# comparing that character
with # the character
in guesses if char in
guesses:
print(char, end=" ")
else:
print("_")
# for every failure
1 will be # incremented in failure
failed += 1
if failed == 0:
# user will
win the game if failure is 0 # and 'You Win' will be given as output
print("You Win")
# this print the correct word print("The word is: ",
word) break
# if user has input the wrong
alphabet then # it will ask user to
enter another alphabet print()
guess = input("guess a character:")
# every input character will be stored in guesses guesses += guess
# check input
with the character in word if guess not
in word:
turns -= 1
# if the character doesn’t match the word
# then “Wrong” will be given as output print("Wrong")
# this will print the number of # turns left for the user
print("You have", + turns, 'more guesses')
if turns == 0:
print("You Loose")
Output:
What is your name? Gautam
Good Luck! Gautam
Guess the characters
_
_
_
_
_
guess a character:g
g
_
_
_
_
guess a character:e
g
e e
_
_
guess a character:k
g
e e k
_
guess a character:s
g e e k s
You Win
The word is:
geeks
Result :
Thus the program
to implement propositional model
checking algorithm is executed and the
output is obtained.
![]()
Aim:
Write a program to implement Breadth
First Search algorithm using Python.
Algorithm:
Step 1: Start a program
Step 2: Declare the variables.
Step
3: Get the values using input function. Step
4: Then calculate the approximate value.
Step 5: print the result of program using print function
Step 6: Stop the program execution.
Program:
from collections import defaultdict
class Graph:
# Constructor
def init (self):
self.graph = defaultdict(list) def addEdge(self,u,v):
self.graph[u].append(v)
def BFS(self, s):
visited = [False] * (len(self.graph))
queue = []
queue.append(s) visited[s] = True
while queue:
s = queue.pop(0)
print (s, end = " ")
for i in self.graph[s]:
if visited[i] == False:
queue.append(i) visited[i] = True
g
= Graph() g.addEdge(0, 1)
g.addEdge(0, 2)
g.addEdge(1, 2)
g.addEdge(2, 0)
g.addEdge(2, 3)
g.addEdge(3, 3)
print ("Following is Breadth First Traversal"
" (starting from vertex 2)")
g.BFS(2)
Output:
Following is Breadth
First Traversal (starting from vertex 2) 2 0 3 1
Result :
Thus the program
to implement Breadth First
Search algorithm is executed and the output is obtained.
![]()
Aim:
Write a program to implement Depth First Search
algorithm using Python.
Algorithm:
Step 1: Start a program
Step 2: Declare the variables.
Step
3: Get the values using input function. Step
4: Then calculate the approximate value.
Step 5: print the result of program using print function
Step 6: Stop the program execution.
Program:
from collections import defaultdict
class Graph:
# Constructor
def init (self):
self.graph = defaultdict(list)
def addEdge(self, u, v):
self.graph[u].append(v) def
DFSUtil(self, v, visited):
visited.add(v) print(v, end='
')
for neighbour in self.graph[v]:
if neighbour not in visited: self.DFSUtil(neighbour, visited)
def DFS(self, v):
visited = set()
self.DFSUtil(v, visited)
if
name == " main ": g = Graph() g.addEdge(0, 1)
g.addEdge(0, 2)
g.addEdge(1, 2)
g.addEdge(2, 0)
g.addEdge(2, 3)
g.addEdge(3, 3)
print("Following is DFS
from (starting from vertex 2)") # Function call
g.DFS(2)
Output:
Following is Depth First Traversal
(starting from vertex 2) 2 0 1 9 3
Result :
Thus the program to implement Depth First Search algorithm is executed and the output is obtained.
![]()
Aim:
Write a program to implement Build naïve Bayes
models using Python.
Algorithm:
Step 1: Start a program
Step 2: Declare the variables.
Step
3: Get the values using input function. Step
4: Then calculate the approximate value.
Step 5: print the result of program using print function
Step 6: Stop the program execution.
Program:
# Importing
library import math import
random import csv
# the categorical class names are changed to numberic data # eg: yes and no encoded to 1 and 0
def encode_class(mydata):
classes = []
for i in range(len(mydata)):
if mydata[i][-1] not in classes: classes.append(mydata[i][-1])
for i in range(len(classes)):
for j in range(len(mydata)):
if mydata[j][-1] == classes[i]:
mydata[j][-1] = i
return mydata #
Splitting the data
def splitting(mydata, ratio):
train_num = int(len(mydata) * ratio) train = []
# initially
testset will have all the dataset
test = list(mydata)
while len(train) <
train_num:
# index generated randomly from range 0
# to length of testset
index = random.randrange(len(test))
# from testset,
pop data rows and put it in train
train.append(test.pop(index))
return train, test
# Group the data rows under
each class yes or # no in
dictionary eg: dict[yes] and dict[no] def groupUnderClass(mydata):
dict = {}
for i in range(len(mydata)):
if (mydata[i][-1] not in dict): dict[mydata[i][-1]] = []
dict[mydata[i][-1]].append(mydata[i])
return dict
#
Calculating Mean def mean(numbers):
return sum(numbers) / float(len(numbers))
# Calculating Standard Deviation
def std_dev(numbers):
avg = mean(numbers)
variance = sum([pow(x - avg, 2) for
x in numbers]) / float(len(numbers) - 1) return math.sqrt(variance)
def MeanAndStdDev(mydata):
info = [(mean(attribute), std_dev(attribute)) for attribute in zip(*mydata)] # eg:
list = [ [a, b, c], [m, n, o], [x, y, z]]
# here mean of 1st attribute =(a +
m+x), mean of 2nd attribute = (b + n+y)/3 # delete summaries of last class
del info[-1] return info
# find Mean and Standard Deviation
under each class def
MeanAndStdDevForClass(mydata):
info = {}
dict = groupUnderClass(mydata)
for classValue, instances in dict.items():
info[classValue] = MeanAndStdDev(instances)
return info
# Calculate
Gaussian Probability Density
Function def calculateGaussianProbability(x, mean, stdev):
expo = math.exp(-(math.pow(x - mean, 2) / (2 * math.pow(stdev, 2)))) return (1 / (math.sqrt(2 * math.pi) * stdev)) * expo
# Calculate Class Probabilities
def calculateClassProbabilities(info, test): probabilities = {}
for classValue, classSummaries in info.items():
probabilities[classValue] = 1
for i in range(len(classSummaries)):
mean, std_dev = classSummaries[i]
x = test[i]
probabilities[classValue] *= calculateGaussianProbability(x, mean, std_dev)
return probabilities
# Make prediction - highest probability is the prediction def predict(info, test):
probabilities = calculateClassProbabilities(info, test) bestLabel, bestProb = None, -1
for classValue, probability in probabilities.items():
if bestLabel is None or probability > bestProb:
bestProb = probability
bestLabel = classValue
return bestLabel
# returns
predictions for a set of examples
def getPredictions(info, test):
predictions = []
for i in range(len(test)):
result = predict(info, test[i]) predictions.append(result)
return predictions # Accuracy score
def accuracy_rate(test, predictions): correct = 0
for i in range(len(test)):
if test[i][-1] == predictions[i]:
correct += 1
return (correct / float(len(test))) * 100.0
# driver code
# add the data path in your system
filename = r'E:\user\MACHINE LEARNING\machine learning algos\Naive bayes\filedata.csv' # load the file and
store it in mydata list
mydata = csv.reader(open(filename, "rt")) mydata = list(mydata)
mydata = encode_class(mydata) for i in
range(len(mydata)):
mydata[i] = [float(x) for x in mydata[i]]
# split ratio = 0.7
# 70% of data is training
data and 30% is test data
used for testing ratio = 0.7
train_data,
test_data = splitting(mydata, ratio) print('Total number of examples
are: ', len(mydata))
print('Out of these, training
examples are: ', len(train_data))
print("Test examples are: ", len(test_data))
# prepare model
info = MeanAndStdDevForClass(train_data)
# test model
predictions =
getPredictions(info, test_data) accuracy = accuracy_rate(test_data, predictions) print("Accuracy of your
model is: ", accuracy)
Output:
Total number of examples
are: 200
Out of these, training
examples are: 140 Test examples are: 60
Accuracy of your model is: 71.2376788
Result :
Thus the program
to implement Breadth First
Search algorithm is executed and the output is obtained.
![]()
Aim:
Write a program to implement Bayesian
networks and perform
inferences using Python.
Algorithm:
Step 1: Start a program
Step 2: Declare the variables.
Step
3: Get the values using input function. Step
4: Then calculate the approximate value.
Step 5: print the result of program using print function
Step 6: Stop the program execution.
Program:
import numpy as np import csv
import pandas as pd from pgmpy.models import BayesianModel from pgmpy.estimators
import MaximumLikelihoodEstimator from pgmpy.inference
import VariableElimination
#read Cleveland
Heart Disease data heartDisease = pd.read_csv('heart.csv') heartDisease = heartDisease.replace('?',np.nan)
#display the data
print('Few examples from the dataset
are given below') print(heartDisease.head())
#Model Bayesian
Network Model=BayesianModel([('age','trestbps'),('age','fbs'), ('sex','trestbps'),('exang','trestbps'),('trestbps','heartdise
ase'),('fbs','heartdisease'),('heartdisease','restecg'),
('heartdisease','thalach'),('heartdisease','chol')])
#Learning CPDs using Maximum Likelihood Estimators print('\n
Learning CPD using Maximum likelihood estimators') model.fit(heartDisease,estimator=MaximumLikelihoodEstimator) #
Inferencing with Bayesian Network
print('\n Inferencing with Bayesian Network:') HeartDisease_ infer = VariableElimination(model)
#computing the Probability of HeartDisease given Age
print('\n 1. Probability of
HeartDisease given Age=30')
q=HeartDisease_infer.query(variables=['heartdisease'],evidence
={'age':28}) print(q['heartdisease'])
#computing
the Probability of HeartDisease given cholesterol print('\n 2. Probability of HeartDisease given cholesterol=100')
q=HeartDisease_infer.query(variables=['heartdisease'],evidence
={'chol':100}) print(q['heartdisease'])
Result :
Thus the program to implement
Bayesian networks and perform inferences is executed and the output is obtained.
MINI PROJECT
TIC TAC TOE GAME USING PYTHON
Ø INTRODUCTION
The interesting Python project will be build using the
pygame library. We will be explaining all the pygame object methods that are
used in this project. Pygame is a great library that will allow us to create
the window and draw images and shapes on the window. This way we will capture mouse coordinates
and identify the block where we need
to mark ‘X’ or ‘O’. Then we will check
if the user wins the game or not.
Ø PREREQUISITES
To implement this game, we will use the basic concepts
of Python and Pygame which is a Python library for building cross-platform
games. It contains the modules needed for computer graphics and sound
libraries. To install the library,
you can use pip installer from the
command line:
pip install pygame
Ø STEPS TO BUILD A
PYTHON TIC TAC TOE GAME
First, let’s check the steps to build Tic Tac Toe program in Python:
•
Create the display window
for our game.
•
Draw the grid on the canvas where we will play Tic Tac Toe.
•
Draw the status bar below the canvas to show which
player’s turn is it and who wins the game.
•
When someone wins the game or the game is a draw then we reset the game.
We need to run our game inside an infinite loop. It
will continuously look for events and when a user presses the mouse button on
the grid we will first get the X and Y coordinates of the mouse. Then we will
check which square the user has clicked.
Then we will draw the appropriate ‘X’ or ‘O’ image on the canvas. So that is basically
what we will do in this Python project idea.
·
Initializing Game Components
So let’s
start by importing the pygame
library and the time library because we will use the time.sleep() method to pause game at certain positions. Then we initialize all the global variables that we
will use in our Tic Tac Toe game.
import pygame as
pg,sys from pygame.locals import
* import time
#initialize global variables
XO = 'x'
winner = None
draw = False width = 400
height = 400
white = (255, 255, 255)
line_color = (10,10,10)
#TicTacToe 3x3 board
TTT = [[None]*3,[None]*3,[None]*3]
Here, the TTT is the main 3×3 Tic Tac
Toe board and at first, it will have 9 None values. The height and width of the
canvas where we will play the game is 400×400.
·
Initializing Pygame
window
We use the pygame to create a new window where we’ll
play our Tic Tac Toe game. So we initialize the pygame with pg.init() method
and the window display is set with a width of 400 and a height of 500. We have
reserved 100-pixel space for displaying the status of the game.
The pg.display.set_mode() initializes
the display and we reference it with the screen variable. This screen variable
will be used whenever we want to draw
something on the display.
The pg.display.set_caption method is
used to set a name that will appear at the top of the display window.
#initializing pygame window
pg.init()
fps = 30
CLOCK = pg.time.Clock()
screen = pg.display.set_mode((width, height+100),0,32)
pg.display.set_caption("Tic Tac Toe")
·
Load and transform images
The Python project uses many images like the opening
image that will display when the game starts
or resets. The X and O images that we will draw when the user clicks on the
grid. We load all the images and resize them
so that they will fit easily in our window.
#loading the images
opening = pg.image.load('tic tac opening.png')
x_img = pg.image.load('x.png')
o_img = pg.image.load('o.png')
#resizing images
x_img = pg.transform.scale(x_img, (80,80)) o_img = pg.transform.scale(o_img, (80,80))
opening = pg.transform.scale(opening, (width,
height+100))
·
Define the functions
Now we create a function that will start the game. We
will also use this function when we want to restart the game. In pygame, the
blit() function is used on the surface to draw an image on top of another image.
So we draw the opening image and after drawing, we
always need to update the display with pg.display.update(). When the opening
image is drawn, we wait for 1 second using time.sleep(1) and fill the screen
with white colour.
Next, we draw 2 vertical and
horizontal lines on the white background to make the 3×3 grid. In the end, we
call the draw_status() function
def
game_opening(): screen.blit(opening,(0,0))
pg.display.update() time.sleep(1) screen.fill(white)
# Drawing
vertical lines pg.draw.line(screen,line_color,(width/3,0),(width/3, height),7)
pg.draw.line(screen,line_color,(width/3*2,0),(width/3*2, height),7) # Drawing
horizontal lines pg.draw.line(screen,line_color,(0,height/3),(width,
height/3),7) pg.draw.line(screen,line_color,(0,height/3*2),(width,
height/3*2),7) draw_status()
The
draw_status() function draws a black rectangle where we update the
status of the game showing which
player’s turn is it and whether the game ends or draws.
def draw_status(): global
draw
if winner is None:
message = XO.upper() + "'s Turn" else:
message = winner.upper() + " won!" if draw:
message = 'Game Draw!' font = pg.font.Font(None, 30)
text = font.render(message, 1, (255, 255, 255))
# copy the rendered
message onto the board
screen.fill ((0, 0, 0), (0, 400, 500, 100))
text_rect = text.get_rect(center=(width/2, 500-50)) screen.blit(text, text_rect)
pg.display.update()
The check_win() function checks the Tic Tac Toe board
to see all the marks of ‘X’ and ‘O’. It calculates whether a player has won the
game or not. They can either win when the player has marked 3 consecutive marks
in a row, column or diagonally. This function is called every time when we draw
a mark ‘X’ or ‘O’ on the board.
def check_win():
global TTT, winner,draw
# check for winning
rows for row in range (0,3):
if ((TTT [row][0]
== TTT[row][1] == TTT[row][2]) and(TTT [row][0] is not None)): # this row won
winner = TTT[row][0]
pg.draw.line(screen, (250,0,0), (0, (row + 1)*height/3 -height/6),\ (width, (row + 1)*height/3 -
height/6 ), 4)
break
# check for winning
columns for col in range (0, 3):
if (TTT[0][col] == TTT[1][col] == TTT[2][col]) and (TTT[0][col] is not None): # this column won
winner = TTT[0][col] #draw
winning line
pg.draw.line (screen, (250,0,0),((col + 1)* width/3 -
width/6, 0),\ ((col + 1)*
width/3 - width/6, height), 4)
break
# check for diagonal
winners
if (TTT[0][0] == TTT[1][1] == TTT[2][2]) and (TTT[0][0] is not None):
# game won diagonally left to right winner = TTT[0][0]
pg.draw.line (screen, (250,70,70), (50, 50), (350,
350), 4)
if (TTT[0][2] == TTT[1][1] == TTT[2][0]) and (TTT[0][2] is not None):
# game won diagonally right to left winner = TTT[0][2]
pg.draw.line (screen, (250,70,70), (350, 50), (50, 350), 4) if(all([all(row) for row in TTT]) and
winner is None ):
draw = True draw_status()
The drawXO(row, col) function takes the row and column where the
mouse is clicked and then it draws
the ‘X’ or ‘O’ mark. We calculate the x and y coordinates of the starting point
from where we’ll draw the png image of the mark.
def drawXO(row,col):
global TTT,XO
if row==1: posx = 30
if row==2:
posx = width/3
+ 30 if row==3:
posx = width/3*2
+ 30 if col==1:
posy = 30 if col==2:
posy = height/3
+ 30 if col==3:
posy = height/3*2 + 30
TTT[row-1][col-1] = XO if(XO == 'x'):
screen.blit(x_img,(posy,posx))
XO= 'o'
else:
screen.blit(o_img,(posy,posx))
XO= 'x'
pg.display.update() #print(posx,posy) #print(TTT)
The userClick() function
is triggered every time the user presses the mouse
button.
When the user clicks the mouse, we first take the x and y
coordinates of where the mouse is clicked on the display window and then if
that place is not occupied we draw the ‘XO’ on the canvas. We also check if the
player wins or not after drawing ‘XO’ on the board.
def userClick():
#get coordinates of mouse click x,y = pg.mouse.get_pos()
#get column
of mouse click (1-3)
if(x<width/3):
col = 1
elif (x<width/3*2): col = 2
elif(x<width): col = 3
else:
col = None
#get row of mouse click (1-3)
if(y<height/3):
row = 1
elif (y<height/3*2): row = 2
elif(y<height): row = 3
else:
row = None #print(row,col)
if(row and col and TTT[row-1][col-1] is None): global XO
#draw the x or o on screen
drawXO(row,col) check_win()
The last function is the reset_game().
This will restart the game and we also reset all the variables to the beginning
of the game.
def reset_game():
global TTT, winner,XO, draw time.sleep(3)
XO = 'x'
draw = False game_opening() winner=None
TTT = [[None]*3,[None]*3,[None]*3]
·
Run the tic tac toe game forever
To start the game, we will call the game_opening()
function. Then, we run an infinite loop and continuously check for any event
made by the user. If the user presses mouse button, the MOUSEBUTTONDOWN event
will be captured and then we will trigger the userClick() function. Then if the user wins or the game draws, we
reset the game by calling reset_game() function. We update the display in each
iteration and we have set the frames per second to 30.
game_opening()
# run the game loop forever while(True):
for event in pg.event.get():
if event.type == QUIT:
pg.quit() sys.exit()
elif event.type == MOUSEBUTTONDOWN:
# the user clicked; place an X or O userClick()
if(winner or draw): reset_game()
pg.display.update() CLOCK.tick(fps)
Save the source code with
the tictactoe.py file name and run the file.
Ø
OUTPUT
![]()
CONCLUSION
With this project in Python, we have successfully made
the Tic Tac Toe game. We used the popular pygame library for rendering graphics
on a display window. We learned how to capture events from the keyboard or mouse
and trigger a function when the
mouse button is pressed. This way we can calculate
mouse position, draw X or O on the display and check if the player wins the game or not. I hope you
enjoyed building the game.
Comments
Post a Comment