0% found this document useful (0 votes)
29 views38 pages

AI Lab Experiments Using Python

The document outlines the objectives and outcomes of the Artificial Intelligence Lab course (BCS 751) in the Department of Computer Science & Engineering, emphasizing the development of engineering knowledge, problem-solving skills, and ethical practices. It details the program outcomes (POs), program-specific outcomes (PSOs), and course outcomes (COs) related to AI techniques and algorithms implemented using Python. Additionally, it includes a comprehensive list of experiments designed to apply theoretical concepts in practical scenarios, such as search algorithms, natural language processing, and optimization techniques.

Uploaded by

aryankingroyal
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)
29 views38 pages

AI Lab Experiments Using Python

The document outlines the objectives and outcomes of the Artificial Intelligence Lab course (BCS 751) in the Department of Computer Science & Engineering, emphasizing the development of engineering knowledge, problem-solving skills, and ethical practices. It details the program outcomes (POs), program-specific outcomes (PSOs), and course outcomes (COs) related to AI techniques and algorithms implemented using Python. Additionally, it includes a comprehensive list of experiments designed to apply theoretical concepts in practical scenarios, such as search algorithms, natural language processing, and optimization techniques.

Uploaded by

aryankingroyal
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

Department of Computer Science & Engineering

Artificial Intelligence Lab Using PYTHON (BCS 751)

Som Hunka
Name

2200330100222
Roll No.

4 [D]
Section- Batch
Department of Computer Science and Engineering

To lead i n the fiel d of Com puter Science and Engi neeri ng by


fostering a culture of excellence, creati vity, and ethi cal val ues to
produce graduates equi ppe d with cutti ng-edge knowl edge and
innovati ve thi nki ng, poised to address global challenges i n
technology through research, education, and practical applications.

To culti vate a dynamic learni ng environment usi ng cutti ng -edge


resources to i nspire and educate moti vated, knowledgeable, and
value-dri ven professionals in computer science and engineeri ng.

To coll aborate with i ndustry, professional s, academi c i nstitutions,


and society, promoti ng the exchange of knowledge, advanci ng
academic processes, and enabling i mpactful research and
technological solutions.

To foster a culture of i nnovation, entrepreneurshi p, leadershi p,


and social responsibility, preparing students to address real -world
challenges and contribute to the betterment of society.
Department of Computer Science & Engineering

PROGRAM OUTCOMES (POs):

Engineering Graduates will be able to:

PO1: Engineering knowledge: Apply the knowledge of mathematics, science,


engineering fundamentals, and an engineering specialization to the solution of
complex engineering problems.

PO2: Proble m analysis: Identify, formulate, review research literature, and analyze
complex engineering problems reaching substantiated conclusions using first
principles of mathematics, natural sciences, and engineering sciences.

PO3: Design/development of solutions: Design solutions for complex engineering


problems and design system components or processes that meet the specified needs
with appropriate consideration for the public health and safety, and the cultural,
societal, and environmental considerations.

PO4: Conduct investigations of complex problems: Use research-based


knowledge and research methods including design of experiments, analysis and
interpretation of data, and synthesis of the information to provide valid conclusions.

PO5: Modern tool usage: Create, select, and apply appropriate techniques,
resources, and modern engineering and IT tools including prediction and modelling
to complex engineering activities with an understanding of the limitations.

PO6: The engineer and society: Apply reasoning informed by the contextual
knowledge to assess societal, health, safety, legal and cultural issues and the
consequent responsibilities relevant to the professional engineering practice.

PO7: Environme nt and sustainability: Understand the impact of the professional


engineering solutions in societal and environmental contexts, and demonstrate the
knowledge of, and need for sustainable development.

PO8: Ethics: Apply ethical principles and commit to professional ethics and
responsibilities and norms of the engineering practice.

PO9: Individual and team work: Function effectively as an individual, and as a


member or leader in diverse teams, and in multidisciplinary settings.

PO10: Communication: Communicate effectively on complex engineering


activities with the engineering community and with society at large, such as, being
able to comprehend and write effective reports and design documentation, make
effective presentations, and give and receive clear instructions.
Department of Computer Science & Engineering

PO11: Project manage ment and finance: Demonstrate knowledge and


understanding of the engineering and management principles and apply these
to one’s own work, as a member and leader in a team, to manage projects and
in multidisciplinary environments.
PO12: Life-long learning: Recognize the need for, and have the preparation
and ability to engage in independent and life- long learning in the broadest
context of technological change.

PROGRAM SPECIFIC OUTCOMES (PSOs):

PSO1: The ability to use standard practices and suitable programming


environment to develop software solutions.

PSO2: The ability to employ latest computer languages and platforms in


creating innovative career opportunities.

COURSE OUTCOMES (COs):

Understand and apply basic search algorithms and intelligent problem-solving


CO1
approaches in Python
Design and implement logic-based knowledge representations and reasoning
CO2
using Python and Prolog.

Use Natural Language Toolkit (NLTK) for basic NLP tasks like stemming,
CO3
tagging, and classification

Analyze and implement basic AI game strategies like Minimax and Alpha-
CO4
Beta pruning
Demonstrate AI techniques in real- world tasks such as text processing,
CO5
planning, or constraint satisfaction.
Department of Computer Science & Engineering

LIST OF EXPERIMENTS

Expt. Title of Experiments Corresponding


No. CO
1 Implement Breadth First Search (BFS) for a given graph or
CO1
maze
2 Implement Depth First Search (DFS) for a tree or graph
CO1
structure
3 Solve the 8-Puzzle Problem using A* Search Algorithm. CO1
4 Implement Hill Climbing Algorithm for numerical
optimization or pathfinding. CO1

5 Implement Simulated Annealing Algorithm for co nstraint-


based search problems. CO1

6 Solve Water Jug Problem using state-space search (BFS or


CO1
DFS).
7 Write Prolog programs to define family relationships using
CO2
predicates
8 Implement 4-Queens Problem in Prolog using backtracking. CO2
9 Implement Unification Algorithm in Python or Prolog.
CO2
10 Implement Forward and Backward Chaining in a rule-based
CO2
system (manual or code-based).
11 Demonstrate Resolution in Propositional Logic through a
CO2
basic example (e.g., proving a theorem).
12 Remove punctuation and stop words from a paragraph
CO3
using nltk.
13 Perform stemming and lemmatization on user-input text. CO3
14 Apply POS (Part of Speech) tagging using NLTK on a
CO3
given sentence.
15 Build a simple text classifier using NLTK (e.g., classify CO3
messages as spam/ham).
16 Implement Tic-Tac-Toe game with a basic AI opponent. CO4
17 Implement Min-Max (Minimax) Algorithm for decision CO4
making in turn-based games.
18 Enhance the game with Alpha-Beta Pruning to optimize Min-
CO4
Max.
19 Simulate a Vacuum Cleaner Agent that intelligently cleans a
CO5
2D environment.
20 Build a simple chatbot using rules or pre-trained logic (can use
CO5
regex or basic intent matching).
21 Design a Constraint Satisfaction Problem solver, e.g., CO5
Sudoku, or Map Coloring.
22 Perform simple Bayesian reasoning for a probability-based
CO5
decision problem (e.g., medical diagnosis).

Content Beyond
Syllabus
23. Perform operation in Cloud Computing CO5

24. Perform operation in Cyber Security. CO5


INDEX
Expt. Experiments Name Date of Date of Faculty
No. Conduction Submission Signature
1 Implement Breadth First Search (BFS) for a
given graph or maze
2 Implement Depth First Search (DFS) for a tree
or graph structure
3 Solve the 8-Puzzle Problem using A* Search
Algorithm.
4 Implement Hill Climbing Algorithm for
numerical optimization or pathfinding.
5 Implement Simulated Annealing
Algorithm for constraint-based
search problems.
6 Solve Water Jug Problem using state-space
search (BFS or DFS).
7 Write Prolog programs to define family
relationships using predicates
8 Implement 4-Queens Problem in Prolog using
backtracking.
9 Implement Unification Algorithm in Python or
Prolog.
10 Implement Forward and Backward Chaining
in a rule-based system (manual or code-
based).
11 Demonstrate Resolution in Propositional
Logic through a basic example (e.g., proving a
theorem).
12 Remove punctuation and stop words from
a paragraph using nltk.
13 Perform stemming and lemmatization on
user-input text.
14 Apply POS (Part of Speech) tagging using
NLTK on a given sentence.
15 Build a simple text classifier using NLTK
(e.g., classify messages as spam/ham).
16 Implement Tic-Tac-Toe game with a basic AI
opponent.
17 Implement Min-Max (Minimax) Algorithm
for decision making in turn-based games.
18 Enhance the game with Alpha-Beta Pruning to
optimize Min-Max.
19 Simulate a Vacuum Cleaner Agent that
intelligently cleans a 2D environment.
20 Build a simple chatbot using rules or pre-
trained logic (can use regex or basic intent
matching).
21 Design a Constraint Satisfaction Problem
solver, e.g., Sudoku, or Map Coloring.
22 Perform simple Bayesian reasoning for a
probability-based decision problem (e.g.,
medical diagnosis).
Content Beyond Syllabus
23. Perform operation in Cloud Computing

24. Perform operation in Cyber Security.


Experiment 1: Breadth First Search (BFS)
Aim:
To implement Breadth First Search (BFS) for a given graph or maze using Python.

Theory:
BFS is a graph traversal algorithm that explores vertices in the order of their distance from
the source, using a queue. It is commonly used in shortest path finding in unweighted
graphs.

Algorithm:

1. Start from the source node.


2. Put it into a queue and mark as visited.
3. Dequeue a node, explore all its unvisited neighbors, and enqueue them. 4.
Repeat until the queue is empty.

Python Program:

from collections import deque

def bfs(graph, start):


visited = set()
queue = deque([start])
traversal = []

while queue:
node = [Link]()
if node not in visited:
[Link](node)
[Link](node)
[Link](graph[node] - visited)
return traversal

# Example Graph (Adjacency List with sets)


graph = {
'A': {'B', 'C'},
'B': {'A', 'D', 'E'},
'C': {'A', 'F'},
'D': {'B'},
'E': {'B', 'F'},
'F': {'C', 'E'}
}

print("BFS Traversal:", bfs(graph, 'A'))


Sample Output:

BFS Traversal: ['A', 'B', 'C', 'D', 'E', 'F']


Experiment 2: Depth First Search (DFS)
Aim:
To implement Depth First Search (DFS) for a tree or graph structure using Python.

Theory:
DFS is a graph traversal algorithm that explores as far as possible along each branch before
backtracking, typically implemented with recursion or stack.

Algorithm:

1. Start from the source node.


2. Visit and mark it as visited.
3. Recursively visit all its unvisited neighbors.

Python Program:

def dfs(graph, start, visited=None):


if visited is None:
visited = set()
[Link](start)
print(start, end=" ")
for neighbor in graph[start] - visited:
dfs(graph, neighbor, visited)

graph = {
'A': {'B', 'C'},
'B': {'A', 'D', 'E'},
'C': {'A', 'F'},
'D': {'B'},
'E': {'B', 'F'},
'F': {'C', 'E'}
}

print("DFS Traversal:", end=" ")


dfs(graph, 'A')

Sample Output:

DFS Traversal: A B D E F C
Experiment 3: 8-Puzzle Problem using A Search*
Aim:
To solve the 8-Puzzle Problem using the A* search algorithm with Manhattan
distance heuristic.

Theory:
The 8-puzzle is a sliding puzzle with 8 tiles and a blank space. A* combines cost so far (g)
and estimated cost to goal (h) for efficient pathfinding.

Algorithm:

1. Initialize priority queue with start state.


2. For each state, compute f(n) = g(n) + h(n).
3. Expand the state with the smallest f-value.
4. Repeat until the goal state is reached.

Python Program (Simplified):

import heapq

def manhattan(puzzle, goal):


distance = 0
for i, val in enumerate(puzzle):
if val != 0:
goal_idx = [Link](val)
distance += abs(i//3 - goal_idx//3) + abs(i%3 - goal_idx%3) return
distance

def astar(start, goal):


heap = [(manhattan(start, goal), 0, start, [])]
visited = set()

while heap:
f, g, state, path = [Link](heap)
if state == goal:
return path + [state]
[Link](tuple(state))

zero = [Link](0)
x, y = divmod(zero, 3)
moves = [(-1,0),(1,0),(0,-1),(0,1)]
for dx, dy in moves:
nx, ny = x+dx, y+dy
if 0 <= nx < 3 and 0 <= ny < 3:
new_state = state[:]
nz = nx*3 + ny
new_state[zero], new_state[nz] = new_state[nz], new_state[zero] if
tuple(new_state) not in visited:
[Link](heap, (g+1+manhattan(new_state, goal), g+1, new_state, path+[state]))
return None

start = [1,2,3,4,0,5,6,7,8]
goal = [1,2,3,4,5,6,7,8,0]
solution = astar(start, goal)
for step in solution:
print(step[0:3], step[3:6], step[6:9])

Sample Output (Steps to Solution):

[1, 2, 3] [4, 0, 5] [6, 7, 8]


[1, 2, 3] [4, 5, 0] [6, 7, 8]
[1, 2, 3] [4, 5, 8] [6, 7, 0]
[1, 2, 3] [4, 5, 6] [7, 8, 0]
Experiment 4: Hill Climbing Algorithm
Aim:
To implement Hill Climbing for numerical optimization.

Theory:
Hill Climbing is a local search algorithm that iteratively moves towards increasing value (or
decreasing cost). It may get stuck in local optima.

Algorithm:

1. Start with an initial solution.


2. Generate neighbors.
3. Move to the neighbor with better evaluation.
4. Stop if no improvement.

Python Program (maximize f(x) = -(x-3)^2 + 9):


import random

def f(x):
return -(x-3)**2 + 9

def hill_climb():
x = [Link](-10, 10)
step = 0.1
for _ in range(1000):
new_x = x + [Link]([-step, step])
if f(new_x) > f(x):
x = new_x
return x, f(x)

solution = hill_climb()
print("Optimal x:", solution[0], "f(x):", solution[1])

Sample Output:

Optimal x: 2.98 f(x): 8.999


Experiment 5: Simulated Annealing
Aim:
To implement Simulated Annealing for optimization problems.

Theory:
Simulated Annealing is a probabilistic technique inspired by metallurgy. It
allows occasional "worse" moves to escape local optima, controlled by a
temperature parameter that decreases over time.

Algorithm:

1. Start with a random solution and initial temperature.


2. At each step, generate a neighbor.
3. Accept if better; if worse, accept with probability exp(-ΔE/T). 4.
Reduce temperature and repeat.

Python Program:
import math, random

def f(x):
return -(x-3)**2 + 9 # maximize this function

def simulated_annealing():
x = [Link](-10, 10)
T = 100.0
cooling = 0.99
while T > 0.001:
new_x = x + [Link](-1, 1)
delta = f(new_x) - f(x)
if delta > 0 or [Link]() < [Link](delta/T):
x = new_x
T *= cooling
return x, f(x)

solution = simulated_annealing()
print("Optimal x:", solution[0], "f(x):", solution[1])

Sample Output:

Optimal x: 3.001 f(x): 8.999


Experiment 6: Water Jug Problem (using BFS)
Aim:
To solve the Water Jug Problem using State-Space Search (BFS).

Theory:

∙ You are given two jugs of capacities m and n.


∙ The objective is to measure exactly d liters of water.
∙ BFS explores states (x, y) where x and y are amounts of water in jug1 and jug2.

Algorithm:

1. Start with (0,0).


2. Possible operations:
o Fill a jug.
o Empty a jug.
o Pour water from one jug to another.
3. Apply BFS until a state with target is found.

Python Program:

from collections import deque

def water_jug_bfs(m, n, d):


visited = set()
queue = deque([(0, 0)])
path = []

while queue:
x, y = [Link]()
if (x, y) in visited:
continue
[Link]((x, y))
[Link]((x, y))

if x == d or y == d:
return path

# possible operations
states = [
(m, y), (x, n), (0, y), (x, 0),
(x - min(x, n - y), y + min(x, n - y)), (x + min(y,
m - x), y - min(y, m - x)) ]

for s in states:
if s not in visited:
[Link](s)
return None

solution = water_jug_bfs(4, 3, 2)
print("Steps:", solution)
Sample Output:

Steps: [(0, 0), (4, 0), (1, 3), (1, 0), (0, 1), (4, 1), (2, 3)]
Experiment 7: Prolog – Family Relationships
Aim:
To define family relationships using Prolog predicates.

Theory:
Prolog uses facts and rules to define relationships such as parent, grandparent, sibling.

Prolog Program ([Link]):

parent(john, mary).
parent(john, peter).
parent(mary, susan).
parent(peter, tom).

male(john).
male(peter).
male(tom).
female(mary).
female(susan).

father(X,Y) :- parent(X,Y), male(X).


mother(X,Y) :- parent(X,Y), female(X).
grandparent(X,Y) :- parent(X,Z), parent(Z,Y).
sibling(X,Y) :- parent(Z,X), parent(Z,Y), X \= Y.

Sample Queries:

?- father(john, mary).
true.

?- grandparent(john, susan).
true.

?- sibling(mary, peter).
true.
Experiment 8: 4-Queens Problem in Prolog (Backtracking)
Aim:
To solve the 4-Queens Problem in Prolog using backtracking.

Theory:

∙ Place 4queens on a 4×4 chessboard so that no two queens attack each other. ∙
Prolog’s backtracking checks all permutations until a valid solution is found.

Prolog Program ([Link]):

safe([]).
safe([X|Xs]) :- safe(Xs), noattack(X, Xs, 1).

noattack(_, [], _).


noattack(X, [Y|Ys], N) :-
X =\= Y,
abs(X-Y) =\= N,
N1 is N+1,
noattack(X, Ys, N1).

queens(N, Solution) :-
range(1, N, Ns),
permutation(Ns, Solution),
safe(Solution).

range(M, M, [M]).
range(M, N, [M|Ns]) :- M < N, M1 is M+1, range(M1, N, Ns).

Sample Query:

?- queens(4, Solution).
Solution = [2, 4, 1, 3] ;
Solution = [3, 1, 4, 2].
Experiment 9: Unification Algorithm (Prolog/Python)
Aim:
To implement Unification algorithm to check whether two terms can be unified.

Theory:
Unification is the process of making two terms identical by finding substitutions.

Prolog Program:

unify(X, X).
unify(X, Y) :- var(X), X = Y.
unify(X, Y) :- var(Y), X = Y.
unify([H1|T1], [H2|T2]) :- unify(H1, H2), unify(T1, T2).

Sample Queries:

?- unify(f(X, a), f(b, Y)).


X = b,
Y = a.
Experiment 10: Forward & Backward Chaining

Aim:
To implement Forward and Backward Chaining in a rule-based expert system.

Theory:

∙ Forward
chaining: Start with known facts, apply rules until goal is reached. ∙
Backward chaining: Start with goal, check if facts/rules can support it.

Python Program (Simple Example):

facts = {"fever", "cough"}


rules = {
"flu": ["fever", "cough"],
"cold": ["cough"]
}

def forward_chaining(facts, rules):


inferred = set()
for conclusion, conditions in [Link]():
if all(c in facts for c in conditions):
[Link](conclusion)
return inferred

print("Forward Chaining Result:", forward_chaining(facts, rules))

def backward_chaining(goal, facts, rules):


if goal in facts:
return True
if goal in rules:
return all(backward_chaining(c, facts, rules) for c in rules[goal]) return
False

print("Backward Chaining flu?", backward_chaining("flu", facts, rules))

Sample Output:

Forward Chaining Result: {'flu', 'cold'}


Backward Chaining flu? True
Experiment 11: Resolution in Propositional Logic
Aim:
To demonstrate resolution in propositional logic through a simple example.

Theory:

∙ Resolutionis a rule of inference used in propositional logic and predicate logic. ∙ It


works by refuting the negation of the statement we want to prove. ∙ Clauses are expressed
in Conjunctive Normal Form (CNF).

Algorithm:

1. Convert given statements to CNF.


2. Negate the statement to be proved and add it to the knowledge base. 3.
Repeatedly apply resolution until:
o Empty clause found (goal proved), or
o No progress possible.

Python Program (Simple Example):

def resolution(kb, query):


clauses = kb + [negate(query)]
new = set()
while True:
n = len(clauses)
for i in range(n):
for j in range(i+1, n):
resolvents = resolve(clauses[i], clauses[j]) if [] in
resolvents:
return True
[Link](map(tuple, resolvents))
if [Link](set(map(tuple, clauses))):
return False
for c in new:
if list(c) not in clauses:
[Link](list(c))

def negate(literal):
return ["~" + literal] if not [Link]("~") else [literal[1:]]

def resolve(ci, cj):


resolvents = []
for di in ci:
for dj in cj:
if di == "~"+dj or dj == "~"+di:
resolvent = list(set(ci + cj))
[Link](di)
[Link](dj)
[Link](resolvent)
return resolvents

# Example KB: (A or B), (~A), (~B) => Prove contradiction kb =


[["A", "B"], ["~A"], ["~B"]]
query = "C"
print("Resolution Result:", resolution(kb, query))

Sample Output:

Resolution Result: True


Experiment 12: Removing Punctuation & Stopwords
using NLTK
Aim:
To remove punctuation and stop words from a paragraph using Python NLTK.

Theory:

∙ Preprocessing is the first step in NLP.


∙ Stopwords are common words like the, is, an.
∙ Removing punctuation and stopwords helps in meaningful text analysis. Python

Program:

import nltk
import string
from [Link] import stopwords
[Link]('stopwords')
[Link]('punkt')

text = "This is an example sentence, showing off the stop words filtration."
tokens = nltk.word_tokenize(text)

# remove punctuation
tokens = [word for word in tokens if [Link]()]
# remove stopwords
filtered = [word for word in tokens if [Link]() not in [Link]('english')]

print("Original:", text)
print("After Cleaning:", filtered)

Sample Output:

Original: This is an example sentence, showing off the stop words filtration. After
Cleaning: ['example', 'sentence', 'showing', 'stop', 'words', 'filtration']
Experiment 13: Stemming and Lemmatization
Aim:
To perform stemming and lemmatization on user-input text using NLTK.

Theory:

∙ Stemming: Reduces words to their root form by cutting suffixes (e.g., “running” → “run”).
∙ Lemmatization: Uses vocabulary and morphology to reduce words (e.g., “better” → “good”).

Python Program:

from [Link] import PorterStemmer, WordNetLemmatizer


from [Link] import wordnet
[Link]('wordnet')

text = ["running", "flies", "better", "studies"]

stemmer = PorterStemmer()
lemmatizer = WordNetLemmatizer()

print("Word | Stem | Lemma")


for w in text:
print(w, "|", [Link](w), "|", [Link](w, pos='v')) Sample

Output:

Word | Stem | Lemma


running | run | run
flies | fli | fly
better | better | good
studies | studi | study
Experiment 14: POS Tagging using NLTK
Aim:
To apply Part-of-Speech (POS) tagging on a given sentence using NLTK.

Theory:
POS tagging assigns grammatical categories (noun, verb, adjective, etc.) to words in
a sentence.

Python Program:

[Link]('averaged_perceptron_tagger')

sentence = "Artificial Intelligence is transforming the world."


tokens = nltk.word_tokenize(sentence)
tags = nltk.pos_tag(tokens)

print("POS Tagging:", tags)

Sample Output:

POS Tagging: [('Artificial', 'JJ'), ('Intelligence', 'NNP'), ('is',


'VBZ'), ('transforming', 'VBG'), ('the', 'DT'), ('world', 'NN'), ('.', '.')]
Experiment 15: Text Classification (Spam/Ham) using NLTK
Aim:
To build a simple text classifier using NLTK to classify messages as spam or ham.

Theory:

∙ Text classification is done using features like word presence.


∙ NLTK provides a NaiveBayesClassifier.

Python Program:

from [Link] import NaiveBayesClassifier


from [Link] import names

def features(word):
return {'last_letter': word[-1]}

train = [({'contains_free': True}, 'spam'),


({'contains_free': False}, 'ham'),
({'contains_offer': True}, 'spam'),
({'contains_offer': False}, 'ham')]

classifier = [Link](train)

test1 = {'contains_free': True}


test2 = {'contains_offer': False}

print("Test1 classified as:", [Link](test1))


print("Test2 classified as:", [Link](test2))

Sample Output:

Test1 classified as: spam


Test2 classified as: ham
Experiment 16: Tic-Tac-Toe Game with Basic AI Opponent
Aim:
To implement Tic-Tac-Toe game in Python with a simple AI opponent.

Theory:

∙ Tic-Tac-Toe is a two-player game (3×3 grid).


∙ The AI can play randomly or use simple heuristics.

Python Program:

import random

def print_board(board):
for i in range(3):
print(board[3*i:3*i+3])

def check_winner(board, player):


win_conditions = [
[0,1,2],[3,4,5],[6,7,8], # rows
[0,3,6],[1,4,7],[2,5,8], # cols
[0,4,8],[2,4,6] # diagonals
]
return any(all(board[pos] == player for pos in combo) for combo in win_conditions)

def tic_tac_toe():
board = [" "]*9
while " " in board:
# Human move
move = int(input("Enter your move (0-8): "))
if board[move] == " ":
board[move] = "X"
if check_winner(board, "X"):
print_board(board)
return "Human wins!"

# AI move (random)
ai_move = [Link]([i for i in range(9) if board[i] == "
"]) board[ai_move] = "O"
if check_winner(board, "O"):
print_board(board)
return "AI wins!"
print_board(board)
return "Draw!"

print(tic_tac_toe())

Sample Output (Example Playthrough):

['X', 'O', ' ']


[' ', ' ', ' ']
[' ', ' ', ' ']
...
Result: AI wins!
Experiment 17: Minimax Algorithm for Tic-Tac-Toe
Aim:
To implement Minimax algorithm for decision-making in Tic-Tac-Toe.

Theory:

∙ Minimax is a recursive algorithm for two-player zero-sum games. ∙ One


player maximizes score, the other minimizes it.

Python Program:
def minimax(board, depth, is_maximizing): if
check_winner(board, "X"):
return -1
if check_winner(board, "O"):
return 1
if " " not in board:
return 0

if is_maximizing:
best = -999
for i in range(9):
if board[i] == " ":
board[i] = "O"
score = minimax(board, depth+1, False) board[i] = " "
best = max(best, score)
return best
else:
best = 999
for i in range(9):
if board[i] == " ":
board[i] = "X"
score = minimax(board, depth+1, True) board[i] = " "
best = min(best, score)
return best

def best_move(board):
best_val = -999
move = -1
for i in range(9):
if board[i] == " ":
board[i] = "O"
score = minimax(board, 0, False) board[i] = "
"
if score > best_val:
best_val = score
move = i
return move

Sample Output:

AI chooses position 4 (center)


Experiment 18: Alpha-Beta Pruning in Minimax
Aim:
To optimize the Minimax algorithm using Alpha-Beta Pruning.

Theory:

∙ Alpha-Beta pruning avoids exploring branches that cannot influence the final decision.
∙ Reduces computation while maintaining correctness.

Python Program:

def minimax_ab(board, depth, alpha, beta, is_maximizing):


if check_winner(board, "X"):
return -1
if check_winner(board, "O"):
return 1
if " " not in board:
return 0

if is_maximizing:
max_eval = -999
for i in range(9):
if board[i] == " ":
board[i] = "O"
eval = minimax_ab(board, depth+1, alpha, beta, False) board[i] = " "
max_eval = max(max_eval, eval)
alpha = max(alpha, eval)
if beta <= alpha:
break
return max_eval
else:
min_eval = 999
for i in range(9):
if board[i] == " ":
board[i] = "X"
eval = minimax_ab(board, depth+1, alpha, beta, True) board[i] = " "
min_eval = min(min_eval, eval)
beta = min(beta, eval)
if beta <= alpha:
break
return min_eval
Sample Output:

AI chooses optimal move using Alpha-Beta Pruning


Experiment 19: Vacuum Cleaner Agent Simulation
Aim:
To simulate a vacuum cleaner agent that intelligently cleans a 2D environment.

Theory:

∙ The agent can move Left/Right and Clean.


∙ The environment is a simple 2-cell world.

Python Program:

def vacuum_cleaner(env, start):


pos = start
steps = []
for _ in range(2):
if env[pos] == 1:
[Link](f"Clean at {pos}")
env[pos] = 0
if pos == 0:
pos = 1
[Link]("Move Right")
else:
pos = 0
[Link]("Move Left")
return steps

environment = [1, 1] # 1 = dirty, 0 = clean


print("Actions:", vacuum_cleaner(environment, 0))

Sample Output:

Actions: ['Clean at 0', 'Move Right', 'Clean at 1', 'Move Left']


Experiment 20: Simple Chatbot
Aim:
To build a simple rule-based chatbot using Python.

Theory:

∙ Chatbotscan be built using pattern matching or ML/NLP techniques. ∙ Here,


we use simple rule-based responses.

Python Program:

def chatbot(user_input):
user_input = user_input.lower()
if "hello" in user_input:
return "Hello! How can I help you?"
elif "your name" in user_input:
return "I am a simple AI chatbot."
elif "bye" in user_input:
return "Goodbye! Have a nice day."
else:
return "I didn't understand that."

while True:
msg = input("You: ")
if [Link]() == "bye":
print("Bot:", chatbot(msg))
break
print("Bot:", chatbot(msg))

Sample Output:

You: hello
Bot: Hello! How can I help you?
You: what is your name?
Bot: I am a simple AI chatbot.
You: bye
Bot: Goodbye! Have a nice day.
Experiment 21: Constraint Satisfaction Problem
(Sudoku Solver)
Aim:
To design a CSP solver (Sudoku) using backtracking in Python.

Theory:

∙A CSP consists of:


o Variables (cells of Sudoku).
o Domains (values 1–9).
o Constraints (row, column, subgrid uniqueness).
∙ Backtracking is commonly used for solving Sudoku and Map Coloring.

Algorithm:

1. Select an empty cell.


2. Try numbers from 1–9.
3. If valid (row/column/box constraints satisfied), place the number. 4.
Recursively solve for the next cell.
5. If no valid number, backtrack.

Python Program (Sudoku Solver):

def print_board(board):
for row in board:
print(row)

def is_valid(board, row, col, num):


# Check row
if num in board[row]:
return False
# Check column
if num in [board[r][col] for r in range(9)]:
return False
# Check 3x3 box
start_row, start_col = 3*(row//3), 3*(col//3)
for i in range(3):
for j in range(3):
if board[start_row+i][start_col+j] == num:
return False
return True

def solve(board):
for row in range(9):
for col in range(9):
if board[row][col] == 0: # empty cell for num in
range(1, 10):
if is_valid(board, row, col, num): board[row][col]
= num if solve(board):
return True
board[row][col] = 0 return False
return True

# Example Sudoku puzzle (0 = empty)


sudoku = [
[5,3,0,0,7,0,0,0,0],
[6,0,0,1,9,5,0,0,0],
[0,9,8,0,0,0,0,6,0],
[8,0,0,0,6,0,0,0,3],
[4,0,0,8,0,3,0,0,1],
[7,0,0,0,2,0,0,0,6],
[0,6,0,0,0,0,2,8,0],
[0,0,0,4,1,9,0,0,5],
[0,0,0,0,8,0,0,7,9]
]

solve(sudoku)
print_board(sudoku)

Sample Output (Solved Sudoku):

[5, 3, 4, 6, 7, 8, 9, 1, 2]
[6, 7, 2, 1, 9, 5, 3, 4, 8]
[1, 9, 8, 3, 4, 2, 5, 6, 7]
[8, 5, 9, 7, 6, 1, 4, 2, 3]
[4, 2, 6, 8, 5, 3, 7, 9, 1]
[7, 1, 3, 9, 2, 4, 8, 5, 6]
[9, 6, 1, 5, 3, 7, 2, 8, 4]
[2, 8, 7, 4, 1, 9, 6, 3, 5]
[3, 4, 5, 2, 8, 6, 1, 7, 9]
Experiment 22: Bayesian Reasoning (Medical
Diagnosis Example)
Aim:
To perform Bayesian reasoning for probability-based decision-making.

Theory:

∙ Bayes’ Theorem:

P(H∣E)=P(E∣H)⋅P(H)P(E)P(H|E) = \frac{P(E|H) \cdot


P(H)}{P(E)}P(H∣E)=P(E)P(E∣H)⋅P(H)

∙ Used in medical diagnosis, spam filtering, decision-making.

Example:

∙ Disease D affects 1% of population → P(D) = 0.01


∙ Test is 90% accurate if person has disease → P(Positive|D) = 0.9 ∙ Test
gives 5% false positive → P(Positive|¬D) = 0.05
∙ Find: P(D|Positive).

Python Program:

def bayes_theorem(p_disease, p_pos_given_disease,


p_pos_given_no_disease): p_no_disease = 1 - p_disease
p_pos = p_pos_given_disease * p_disease + p_pos_given_no_disease * p_no_disease return
(p_pos_given_disease * p_disease) / p_pos

p_disease = 0.01
p_pos_given_disease = 0.9
p_pos_given_no_disease = 0.05

result = bayes_theorem(p_disease, p_pos_given_disease, p_pos_given_no_disease)


print("Probability of Disease given Positive Test:", round(result, 4))

Sample Output:

Probability of Disease given Positive Test: 0.1538

You might also like