Ai File HM
Ai File HM
(Approved by AICTE & Affiliated to Dr. APJ Abdul Kalam Technical University (Formerly UPTU), Lucknow)
Department of CSE (Artificial Intelligence)
INDEX
Student Roll no :- 2101611520031 Student name :-Nikunj kumar
Subject name :- Artificial Intelligence Lab Subject code :- KAI551
Impleme-
Practical Output Viva Total
Practical name Date ntation Signature
No. (5 MM) (5 MM) (20 MM)
(10 MM)
Write a python program to
1 implement Breadth First
Search Traversal.
Write a python program to
2 implement Water Jug
Problem.
Write a python program to
3 remove punctuations from the
given string.
Write a python program to sort
4 the sentence in alphabetical
order.
Practical :- 1
Name of the practical :- Implementing BFS Traversal
Student Roll no :- 2101611520031
Student Name :- Nikunj kumar
Semester/Batch :- 5th semester (2021-2025)
About: Breadth-First Search explores a graph level by level, visiting all neighbors of a node
before moving on to the next depth, ensuring the shortest path is found efficiently.
CODE:
graph = { #creating dictionary
'a': ['f','c','b'],
'b': ['a','c','g'],
'c': ['a','b','d','e','f','g'],
'd': ['c','f','e','j'],
'e': ['c','d','g','j','k'],
'f': ['a','c','d'],
'g': ['b','c','e','k'],
'j': ['d','e','k'],
'k': ['e','g','j']
}
OUTPUT:
This is the Breadth-First Search traversal.
a f c b d e g j k
Practical :- 2
Name of the practical :- implementing Water Jug Problem
Student Roll no :- 2101611520031
Student Name :- Nikunj kumar
Semester/Batch :- 5th semester (2021-2025)
About: The Water Jug Problem is like a puzzle where we have two jugs, one holding 5 units
and the other 2 units, and the goal is to measure exactly 1 unit of water. We can fill the jugs,
empty them, and pour water between them. The challenge is to find a sequence of these
operations to reach the desired amount, testing your problem-solving skills
.
CODE:
# Water Jug Problem
from collections import defaultdict
OUTPUT:
Steps:
0 0
5 0
5 2
0 2
2 0
2 2
4 0
4 2
5 1
0 1
True
Practical :- 3
Name of the practical :- Program to remove Punctuations
Student Roll no :- 2101611520031
Student Name :- Nikunj kumar
Semester/Batch :- 5th semester (2021-2025)
CODE:
# Write a Python program to remove punctuation
# Creating a list of common punctuation
punctuation_list = ['@', "'", '-', '!', ':', ';', '/', '#', '.', ',', '?', '$', '%', '^', '&', '*', '(', ')', '[', ']', '{', '}']
string = input("Enter your statement: ") # Taking input from the user
result = " " # Initializing the result
for i in string: # Iterating each character in the input string
# Checking if the character is not in the punctuation list
if i not in punctuation_list:
result = result + i
print(result) # Printing the result without punctuations
OUTPUT:
Enter your statement: Hello! , My name is Nikunj kumar #python
programming
Hello My name is Nikunj kumar python programming
Practical :- 4
Name of the practical :- Program to sort the sentence in alphabetical order
Student Roll no :- 2101611520031
Student Name :- Nikunj kumar
Semester/Batch :- 5th semester (2021-2025)
sentence = input("Enter your sentence: ") # Take input from the user
words = sentence.split() # Split the sentence into words
words.sort() # Sort the words alphabetically
result = " " # Initialize result
for i in words: # Iterate the sorted words and concatenate them
result = result + " " + i
print(result) # Print result
OUTPUT:
Enter your sentence: Python is an object oriented programming language
Python an is language object oriented programming
Practical :- 5
Name of the practical :- Implementing Hangman game using python
Student Roll no :- 2101611520031
Student Name :- Nikunj kumar
Semester/Batch :- 5th semester (2021-2025)
About: Hangman is a classic word game where players guess letters to reveal a hidden word.
Each incorrect guess lost the number of attempts.
CODE:
import random
import string
# Generate a random list of words
def generate_random_words():
num_words = random.randint(5, 10) # Adjust the range as needed
min_length = 3
max_length = 6
words = [''.join(random.choice(string.ascii_lowercase) for _ in
range(random.randint(min_length, max_length))) for _ in range(num_words)]
return words
words = generate_random_words()
guessed_word = random.choice(words)
print("Secret word:", guessed_word)
# Generate a hint
hint = guessed_word[0] + guessed_word[-1]
print("Hint:", hint)
store_g = [] # Empty list to store correct letters
try_p = 4 # Attempts
name = input("Enter your name: ")
print(f"Welcome to the hangman game, {name}! You have only 4 attempts.")
if letter in guessed_word:
print("Yes! '{0}' is in the word.".format(letter))
store_g.append(letter)
else:
print("No! '{0}' is not in the word.".format(letter))
if guess == 2:
print()
clue_request = input("Would you like a clue? (yes/no): ")
if clue_request.lower().startswith('y'):
print("Clue: The first & last letter of the word is:", hint)
else:
print("You are very confident!")
print()
print("Now let's see what you have guessed so far. You have guessed:", len(store_g),
"letter(s) correctly.")
print("These letters are:", ', '.join(store_g))
word_guess = input("Guess the whole word: ")
if word_guess.lower() == guessed_word:
print("Congratulations! You guessed the word correctly.")
else:
print("Sorry! The correct answer was:", guessed_word)
print()
input("Please press enter to leave the game.")
OUTPUT:
Secret word: njo
Hint: no
Enter your name: Nikunj kumar
Welcome to the hangman game, Nikunj kumar! You have only 4 attempts.
Guess a letter: j
Yes! 'j' is in the word.
Guess a letter: t
No! 't' is not in the word.
Guess a letter: w
No! 'w' is not in the word.
Now let's see what you have guessed so far. You have guessed: 1
letter(s) correctly.
These letters are: j
Guess the whole word: njo
Congratulations! You guessed the word correctly.
Practical :- 6
Name of the practical :- Implementing Tic-Tac-Toe game using python
Student Roll no :- 2101611520031
Student Name :- Nikunj kumar
Semester/Batch :- 5th semester (2021-2025)
About: Tic Tac Toe is a classic game played on a 3x3 grid. Two players take turns marking
Xs and Os, aiming to get three in a row horizontally, vertically, or diagonally. The first to
achieve this wins!.
CODE:
. import time
# Initialize board
board = {1: ' ', 2: ' ', 3: ' ',
4: ' ', 5: ' ', 6: ' ',
7: ' ', 8: ' ', 9: ' '}
# Initialize variables
count = 0 # counter to track the number of filled slots
winner = False # boolean to check if anyone won
play = True # boolean to check if the game should continue
tie = False # boolean to check if there is a tie
curr_player = '' # variable to store the current player identifier
player_details = [] # list to store player identifier and marker
# Helper functions
def get_player_details(curr_player):
"""Function to get player identifier and marker"""
if curr_player == 'A':
return ['B', 'O']
else:
return ['A', 'X']
def print_board():
"""Function to print the board"""
for i in board:
print(board[i], ' ', end='')
if i % 3 == 0:
print()
def win_game(marker, player_id):
"""Function to check for a winning combination"""
if (board[1] == board[2] == board[3] == marker or
Faculty Remarks & Signature
KRISHNA ENGINEERING COLLEGE
(Approved by AICTE & Affiliated to Dr. APJ Abdul Kalam Technical University (Formerly UPTU), Lucknow)
Department of CSE – AI
if winner or tie:
play = play_again()
if play:
curr_player = ''
count = 0
OUTPUT:
Practical :- 7
Name of the practical :- Removing stop words for a passage using NLTK
Student Roll no :- 2101611520031
Student Name :- Nikunj kumar
Semester/Batch :- 5th semester (2021-2025)
Aim: Write a python program to remove stop words for a given passage from a text file
using NLTK.
About: Python program uses the Natural Language Toolkit (NLTK) to remove stop words
from a given passage. It first tokenizes the passage, converts it to lowercase, and then filters
out common English stop words. The result is the input passage without stop words.
.
CODE:
#write a python program to remove stop words for a given passage from a text file using
NLTK.
#common pre-processing step
import nltk
nltk.download('punkt')
nltk.download('stopwords')
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
passage= "write a python program to remove stop words for a given passage from a text file
using NLTK"
print(f"input passage: {passage}")
filtered_words=[]
tokens = word_tokenize(passage.lower())
print(f"tokens: {tokens}")
english_stopwords= stopwords.words('english')
for w in tokens:
if w not in english_stopwords:
filtered_words.append(w)
OUTPUT:
input passage: write a python program to remove stop words for a given
passage from a text file using NLTK
tokens: ['write', 'a', 'python', 'program', 'to', 'remove', 'stop',
'words', 'for', 'a', 'given', 'passage', 'from', 'a', 'text', 'file',
'using', 'nltk']
passage without stop words: write python program remove stop words
given passage text file using nltk
[nltk_data] Downloading package punkt to /root/nltk_data...
[nltk_data] Package punkt is already up-to-date!
[nltk_data] Downloading package stopwords to /root/nltk_data...
[nltk_data] Unzipping corpora/stopwords.zip.
Practical :- 8
Name of the practical :- Implement stemming for a given sentence using NLTK
Student Roll no :- 2101611520031
Student Name :- Nikunj kumar
Semester/Batch :- 5th semester (2021-2025)
Aim: Write a python program to implement stemming for a given sentence using NLTK
About: Python program uses the NLTK library to perform stemming on a list of words using
the Porter Stemmer. Stemming involves reducing words to their base or root form. In this
example, words like 'programming,' 'programmer,' and 'programs' are stemmed to their
common root, 'program
.
CODE:
# implementing stemming using NLTK
import nltk
from nltk.stem import PorterStemmer
ps= PorterStemmer()
words=["program","programming","programer","programs","programmed"]
print("{0:30}{1:20}".format("--word--","--stem--"))
for word in words:
print("{0:30}{1:20}".format(word,ps.stem(word)))
OUTPUT:
--word-- --stem--
program program
programming program
programer program
programs program
programmed program
Practical :- 9
Name of the practical :- program to POS tagging for given sentence using NLTK
Student Roll no :- 2101611520031
Student Name :- Nikunj kumar
Semester/Batch :- 5th semester (2021-2025)
Aim: Write a python program to Parts of Speech tagging for the give sentence using NLTK.
About: Python script uses the Natural Language Toolkit (NLTK) to enhance text analysis.
The program processes a sentence, removing common English stopwords, tokenizing the
remaining words, and finally tagging them with their parts of speech using NLTK's pos_tag
function. This helps in understanding the grammatical structure and meaning of each word in
the given sentence.
.
CODE:
#write a python program for parts of a speech tagging for the given sentance using NLTK.
import nltk
nltk.download('stopwords')
nltk.download('punkt')
nltk.download('averaged_perceptron_tagger')
from nltk.corpus import stopwords
from nltk.stem import PorterStemmer
from nltk.tokenize import word_tokenize
english_stop_words = set(stopwords.words('english'))
sentence = "write a python program for parts of a speech tagging for the given sentence using
NLTK."
tokens = word_tokenize(sentence)
words = [w for w in tokens if w.lower() not in english_stop_words]
tagged = nltk.pos_tag(words)
for i in tagged:
print(i)
OUTPUT:
('write', 'JJ')
('python', 'NN')
('program', 'NN')
('parts', 'NNS')
('speech', 'VBP')
('tagging', 'VBG')
('given', 'VBN')
('sentence', 'NN')
('using', 'VBG')
('NLTK', 'NNP')
('.', '.')
Faculty Remarks & Signature
KRISHNA ENGINEERING COLLEGE
(Approved by AICTE & Affiliated to Dr. APJ Abdul Kalam Technical University (Formerly UPTU), Lucknow)
Department of CSE – AI
Practical :- 10
Name of the practical :- Implementing Lemmatization using using NLTK
Student Roll no :- 2101611520031
Student Name :- Nikunj kumar
Semester/Batch :- 5th semester (2021-2025)
CODE:
#Write a python program to implement Lemmatization using NLTK
#Lemmatization is the process of converting a word to its base form
import nltk
from nltk. stem import WordNetLemmatizer
from nltk.tokenize import word_tokenize
print("{0:30}{1:20}".format("--Word--","--Lemmatized--"))
for word in lemmatize_words:
print("{0:30}{1:20}".format(word, lemmatizer.lemmatize (word)))
OUTPUT:
--Word-- --Lemmatized--
program program
programming programming
programer programer
programs program
programmed programmed
Practical :- 11
Name of the practical :- program for Text Classification using NLTK
Student Roll no :- 2101611520031
Student Name :- Nikunj kumar
Semester/Batch :- 5th semester (2021-2025)
Aim: Write a python program to for Text Classification for the give sentence using NLTK.
About: Python script showcases Text Classification using NLTK. It involves organizing a
given sentence into predefined categories or labels. The script uses the NLTK library to
process and analyze the text, allowing for automated categorization based on patterns and
features present in the language.
CODE:
import nltk
import random
nltk.download('movie_reviews')
from nltk.corpus import movie_reviews
documents = [(list(movie_reviews.words(fileid)), category) for category in
movie_reviews.categories() for fileid in movie_reviews.fileids(category)]
random.shuffle(documents)
print(documents[1])
all_words = []
for w in movie_reviews.words():
all_words.append(w.lower())
all_words = nltk.FreqDist(all_words)
print(all_words.most_common(15))
print(all_words["stupid"])
OUTPUT:
[nltk_data] Downloading package movie_reviews to /root/nltk_data...
[nltk_data] Unzipping corpora/movie_reviews.zip. (['this', 'well', '-
', 'conceived', 'but', 'ultra', 'sugary', 'coming', '-', 'of', '-',
'age', 'film', 'is', 'not', 'for', 'everyone', ',', 'and', 'i',
'include', 'myself', 'as', 'one', 'of', 'those', 'who', 'found', 'it',
'too', 'sappy', 'for', 'my', 'digestion', '.', 'joseph', 'cross', '(',
'joshua', 'beal', ')', 'is', 'a', '10', '-', 'year', '-', 'old', 'who',
'is', 'saddened', 'by', 'the', 'recent', 'loss', 'of', 'his',
'grandfather', '(', 'loggia', ')', 'to', 'bone', 'marrow', 'cancer',
'.', 'loggia', 'is', 'wonderful', 'in', 'relating', 'to', 'the',