DEPARTMENT OF COMPUTER SCIENCE AND
ENGINEERING
LAB MANUAL
Third Year CSE- Semester VI
ARTIFICIAL INTELLEGENCE LAB
BCAI551
ACADEMIC YEAR 2025-26
DEPARTMENT OF COMPUTER SCIENCE AND
ENGINEERING
Vision
To acknowledge quality education and instill high patterns of discipline making the
students technologically superior and ethically strong which involves the
improvement in the quality of life in human race.
Mission
❖ To achieve and impart holistic technical education using the best of infrastructure,
outstanding technical and teaching expertise to establish the students in to
competent and confident engineers.
❖ Evolving the center of excellence through creative and innovative teaching learning
practices for promoting academic achievement to produce internationally accepted
competitive and world class professionals.
GENERAL LABORATORY INSTRUCTIONS
1. Students a re-advised to come to the laboratory at least 5 minutes before
(to the starting time), those who come after 5 minutes will not be allowed
into the lab.
2. Plany our task properly much before to the commencement, come prepared to
the lab with the synopsis / program / experiment details.
3. Student should enter in to the laboratory with:
a. Laboratory observation notes with all the details (Problem statement, Aim,
Algorithm, Procedure, Program, Expected Output, etc.,) filled in for the
lab session.
b. Laboratory Record updated up to the last session experiments and other
utensils (if any) needed in the lab.
c. Proper Dress code and Identity card.
4. Sign in the laboratory login register, write the TIME-IN, and occupy the computer
system allotted to you by the faculty.
5. Execute your task in the laboratory, and record the results / output in the lab
observation note book, and get certified by the concerned faculty.
6. All the students should be polite and cooperative with the laboratory staff, must
maintain the discipline and decency in the laboratory.
7. Computer labs are established with sophisticated and high end branded systems,
which should be utilized properly.
8. Students/Faculty must keep their mobile phones in SWITCHED OFF mode
during the lab sessions. Misuse of the equipment, misbehaviors with the staff and
systems etc., will attract severe punishment.
9. Students must take the permission of the faculty in case of any urgency to go out;
if anybody found loitering outside the lab / class without permission during
working hours will be treated seriously and punished appropriately.
10. Students should LOG OFF/ SHUT DOWN the computer system before he/she
leaves the lab after completing the task (experiment) in all aspects. He/she must
ensure the system / seat is kept properly.
HEAD OF THE DEPARTMENT PRINCIPAL
Program Outcomes (POs)
Engineering Knowledge: Apply the knowledge of mathematics, science, engineering
PO1 fundamentals, and an engineering specialization to the solution of complex engineering
problems.
Problem Analysis: Identify, formulate, review research literature, and analyze complex
PO2 engineering problems reaching substantiated conclusions using first principles of
mathematics, natural sciences, and engineering sciences.
Design / Development of Solutions: Design solutions for complex engineering problems and
PO3 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.
Conduct investigations of complex problems: Use research-based knowledge and research
PO4 methods including design of experiments, analysis and interpretation of data, and synthesis of
the information to provide valid conclusions.
Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern
PO5 engineering and IT tools including prediction and modeling to complex engineering activities
with an understanding of the limitations.
The engineer and society: Apply reasoning informed by the contextual knowledge to assess
PO6 societal, health, safety, legal and cultural issues and the consequent responsibilities relevant to
the professional engineering practice.
Environment and sustainability: Understand the impact of the professional engineering
PO7 solutions in societal and environmental contexts, and demonstrate the knowledge of, and
need for sustainable development.
Ethics: Apply ethical principles and commit to professional ethics and responsibilities and norms
PO8 of the engineering practice.
Individual and team work: Function effectively as an individual, and as a member or leader in
PO9 diverse teams, and in multidisciplinary settings.
Communication: Communicate effectively on complex engineering activities with the
PO10 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.
Project management and finance: Demonstrate knowledge and understanding of the engineering
PO11 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.
Course Outcome (CO)
BCAI551 ARTIFICIAL INTELLIGENCE LAB
Course Outcome(CO) Bloom’s Knowledge Level(KL)
At the end of course, the student will be able to
CO1 Use of python to understand the concept of AI K3
CO2 Implementation of Different AI Techniques K4,K5
CO3 Application of AI techniques in practical Life K4
CO4 Understanding of Natural Language Tool Kit. K2
CO5 Practical Application of Natural Language Tool Kit K4,K5
DETAILED SYLLABUS
LIST OF PROGRAMS
1. Write a python program to implement Breadth First Search Traversal?
2. Write a python program to implement Water Jug Problem?
3. Write a python program to remove punctuations from the given string?
4. Write a python program to sort the sentence in alphabetical order?
5. Write a program to implement Hang man game using python.
6. Write a program to implement Tic-Tac-Toe game using python.
7. Write a python program to remove stop words for a given passage from a text file using
NLTK?
8. Write a python program to implement stemming for a given sentence using NLTK?
9. Write a python program to POS (Parts of Speech) tagging for the give sentence using
NLTK?
10. Write a python program to implement Lemmatization using NLTK?
11. WriteapythonprogramtoforTextClassificationforthegivesentenceusingNLTK
Note: The Instructor may add/delete/modify/tune experiments
PROGRAMS
PROGRAM 1: Write a python program to implement Breadth First Search Traversal?
OBJECTIVE:
To implement the Breadth-First Search (BFS) algorithm on a graph using Python. The BFS algorithm is used
to traverse or search graph data structures starting from a selected node and visiting all its neighbors at the
present depth before moving on to the nodes at the next depth level.
class Graph:
def __init__(self):
self.graph = defaultdict(list)
# Function to add an edge to the graph
def add_edge(self, u, v):
self.graph[u].append(v)
# Breadth-First Search traversal
def bfs(self, start):
visited = set() # Set to keep track of visited nodes
queue = deque([start]) # Queue for BFS traversal
visited.add(start)
print("BFS Traversal:", end=" ")
while queue:
vertex = queue.popleft()
print(vertex, end=" ")
# Visit all adjacent vertices
for neighbor in self.graph[vertex]:
if neighbor not in visited:
visited.add(neighbor)
queue.append(neighbor)
PROGRAM 2: Write a python program to implement Water Jug Problem?
OBJECTIVE: To implement a solution for the Water Jug Problem using Breadth-First Search (BFS) strategy
in Python.
from collections import deque
def water_jug_bfs(jug1_capacity, jug2_capacity, target):
# To store visited states
visited = set()
# Use a queue for BFS
queue = deque()
queue.append((0, 0)) # initial state (0, 0)
# Store path of operations
path = []
while queue:
jug1, jug2 = queue.popleft()
# If this state is already visited, skip
if (jug1, jug2) in visited:
continue
# Mark this state as visited
visited.add((jug1, jug2))
# Store current state in path
path.append((jug1, jug2))
# Check if target is reached
if jug1 == target or jug2 == target:
print("Solution found!\nSteps:")
for state in path:
print(state)
return True
# Possible operations
possible_states = [
(jug1_capacity, jug2), # Fill jug1
(jug1, jug2_capacity), # Fill jug2
(0, jug2), # Empty jug1
(jug1, 0), # Empty jug2
(0, jug1 + jug2) if jug1 + jug2 <= jug2_capacity else (jug1 - (jug2_capacity - jug2), jug2_capacity), #
Pour jug1 → jug2
(jug1 + jug2, 0) if jug1 + jug2 <= jug1_capacity else (jug1_capacity, jug2 - (jug1_capacity - jug1)) #
Pour jug2 → jug1
]
for state in possible_states:
if state not in visited:
queue.append(state)
print("No solution found.")
return False
PROGRAM 3: Write a python program to remove punctuations from the given string?
OBJECTIVE: To remove punctuation characters (like .,!?;:'") from a given string using Python.
This is commonly done in text preprocessing, such as for:
• Natural Language Processing (NLP)
• Cleaning user input
• Preparing data for analysis or search
# Define the input string
input_str = "Hello, world! How are you doing today?"
# Define punctuation characters
punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~'''
# Initialize an empty string to store result
no_punct = ""
# Iterate through each character in the string
for char in input_str:
if char not in punctuations:
no_punct += char
# Print the result
print("Original String: ", input_str)
print("String without punctuation: ", no_punct)
PROGRAM 4:
OBJECTIVE: To sort the words in a sentence in alphabetical order using Python.
This is useful in:
• Text processing and analysis
• Organizing words for indexing or searching
• Basic string manipulation practice in programming
# Input sentence
sentence = "Python is a powerful and easy to learn programming language"
# Step 1: Split sentence into words
words = sentence.split()
# Step 2: Sort the list of words
words.sort()
# Step 3: Join the sorted words back into a string
sorted_sentence = ' '.join(words)
# Output the result
print("Original Sentence: ", sentence)
print("Sorted Sentence: ", sorted_sentence)
PROGRAM 5: Write a program to implement Hang man game using python.
OBJECTIVE:
To implement a Hangman word guessing game using Python.
The game helps reinforce:
• String manipulation
• Looping and conditionals
• List usage and control flow
• Basic game logic
import random
# Objective: Implement a basic Hangman game using Python
# Word list for the game
words = ['python', 'computer', 'hangman', 'programming', 'developer']
# Randomly choose a word
word = random.choice(words)
word = word.lower()
# Create a variable with underscores for hidden letters
guessed_word = ['_'] * len(word)
# Set the number of allowed incorrect guesses
attempts = 6
guessed_letters = []
print("Welcome to Hangman!")
print("Guess the word:", ' '.join(guessed_word))
# Game loop
while attempts > 0 and '_' in guessed_word:
guess = input("Enter a letter: ").lower()
# Validate input
if not guess.isalpha() or len(guess) != 1:
print("Please enter a single alphabet.")
continue
if guess in guessed_letters:
print("You already guessed that letter.")
continue
guessed_letters.append(guess)
if guess in word:
# Reveal the letter in the guessed word
for i in range(len(word)):
if word[i] == guess:
guessed_word[i] = guess
print("Good guess:", ' '.join(guessed_word))
else:
attempts -= 1
print(f"Wrong guess. You have {attempts} attempts left.")
print("Current word:", ' '.join(guessed_word))
# End of game
if '_' not in guessed_word:
print("Congratulations! You guessed the word:", word)
else:
print("Sorry, you ran out of attempts. The word was:", word)
PROGRAM 6: Write a program to implement Tic-Tac-Toe game using python.
OBJECTIVE: To implement a two-player Tic-Tac-Toe game using Python, focusing on board management and
game logic
def print_board(board):
for row in board:
print(" | ".join(row))
print("-" * 5)
def check_win(board, player):
for row in board:
if all(cell == player for cell in row):
return True
for col in zip(*board):
if all(cell == player for cell in col):
return True
if all(board[i][i] == player for i in range(3)) or \
all(board[i][2-i] == player for i in range(3)):
return True
return False
def is_full(board):
return all(cell != ' ' for row in board for cell in row)
def play_game():
board = [[' ']*3 for _ in range(3)]
current = 'X'
while True:
print_board(board)
row = int(input(f"Player {current}, enter row (0-2): "))
col = int(input(f"Player {current}, enter col (0-2): "))
if board[row][col] == ' ':
board[row][col] = current
if check_win(board, current):
print_board(board)
print(f"Player {current} wins!")
break
elif is_full(board):
print_board(board)
print("It's a tie!")
break
current = 'O' if current == 'X' else 'X'
else:
print("Cell already taken!")
play_game()
PROGRAM 7: Write a python program to remove stop words for a given passage from a text file using NLTK?
OBJECTIVE: To remove common English stopwords from a passage using the Natural Language Toolkit (NLTK).
import nltk
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
nltk.download('punkt')
nltk.download('stopwords')
# Read from file
with open("passage.txt", "r") as file:
text = file.read()
stop_words = set(stopwords.words("english"))
words = word_tokenize(text)
filtered = [word for word in words if word.lower() not in stop_words]
print("Filtered Sentence:")
print(" ".join(filtered))
PROGRAM 8: Write a python program to implement stemming for a given sentence using NLTK?
OBJECTIVE: To reduce words to their base/root form using stemming.
from nltk.stem import PorterStemmer
from nltk.tokenize import word_tokenize
import nltk
nltk.download('punkt')
sentence = "The boys are playing in the playground while their teacher was watching"
words = word_tokenize(sentence)
stemmer = PorterStemmer()
stemmed_words = [stemmer.stem(word) for word in words]
print("Stemmed Sentence:")
print(" ".join(stemmed_words))
PROGRAM 9: Write a python program to POS (Parts of Speech) tagging for the give sentence using NLTK?
OBJECTIVE: To assign POS tags to each word in a sentence using NLTK.
import nltk
from nltk.tokenize import word_tokenize
nltk.download('punkt')
nltk.download('averaged_perceptron_tagger')
sentence = "The quick brown fox jumps over the lazy dog"
words = word_tokenize(sentence)
pos_tags = nltk.pos_tag(words)
print("POS Tagging:")
for word, tag in pos_tags:
print(f"{word}: {tag}")
PROGRAM 10: Write a python program to implement Lemmatization using NLTK?
OBJECTIVE: To convert words to their base form using lemmatization, considering the context.
from nltk.stem import WordNetLemmatizer
from nltk.tokenize import word_tokenize
import nltk
nltk.download('punkt')
nltk.download('wordnet')
nltk.download('omw-1.4')
lemmatizer = WordNetLemmatizer()
sentence = "The children are playing with toys in the gardens"
words = word_tokenize(sentence)
lemmatized_words = [lemmatizer.lemmatize(word) for word in words]
print("Lemmatized Sentence:")
print(" ".join(lemmatized_words))
PROGRAM 11: Write a python program to for Text Classification for the give sentence using NLTK
OBJECTIVE: To classify text using a simple Naive Bayes classifier in NLTK based on training samples.
import nltk
from nltk.classify import NaiveBayesClassifier
# Training data
train_data = [
({'text': 'I love this phone'}, 'pos'),
({'text': 'This is an amazing movie'}, 'pos'),
({'text': 'I hate this weather'}, 'neg'),
({'text': 'This food is terrible'}, 'neg')
]
# Feature extractor
def extract_features(sentence):
words = sentence.lower().split()
return {word: True for word in words}
# Preparing training set
features = [(extract_features(text['text']), label) for text, label in train_data]
# Train model
classifier = NaiveBayesClassifier.train(features)
# Test
test_sent = "I love this movie"
test_feat = extract_features(test_sent)
print("Classification:", classifier.classify(test_feat))