Programs
Programs
Sc AI
SUBJECT : ARTIFICIAL INTELLIGENCE LAB
SUBJECT CODE : 23UPAI35
LAB EXERCISES
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?
11.Write a python program to for Text Classification for the give sentence using NLTK
1. Write a python program to implement Breadth First Search Traversal?
Aim:
To Write a python program to implement Breadth First Search Traversal
Algorithm:
Step 1: Start by putting any one of the graph’s vertices at the back of the queue.
Step 2: Now take the front item of the queue and add it to the visited list.
Step 3: Create a list of that vertex's adjacent nodes. Add those which are not within the visited list to the rear
of the queue.
Step 4: Keep continuing steps two and three till the queue is empty.
Coding:
graph = {
'5' : ['3','7'],
'3' : ['2', '4'],
'7' : ['8'],
'2' : [],
'4' : ['8'],
'8' : []
}
visited = []
queue = []
def bfs(visited, graph, node):
visited.append(node)
queue.append(node)
while queue:
m = queue.pop(0)
print (m, end = " ")
for neighbour in graph[m]:
if neighbour not in visited:
visited.append(neighbour)
queue.append(neighbour)
print("Following is the Breadth-First Search")
bfs(visited, graph, '5')
Output:
Result :
Hence the program is executed and the output is verified.
2.Write a python program to implement Water Jug Problem?
Aim:
Algorithm:
Step 1: Initialization:
BFS Setup:
Use a queue (deque from collections) to explore each state of the jugs.
Maintain a visited set to avoid processing the same state multiple times.
path dictionary is used to track the previous state for each state, helping in reconstructing
the solution once the target is reached.
Step 2:BFS Exploration:
Queue Initialization:
Start with the initial state (0, 0) where both jugs are empty.
Mark (0, 0) as visited.
Processing States:
Dequeue the current state (jug1, jug2).
Check if either jug1 or jug2 is equal to target. If yes, construct the solution path back to
(0, 0) and return it.
Generating Next States:
Calculate all possible states that can be reached from the current state by:
Filling either jug to its capacity.
Emptying either jug.
Pouring water from one jug to another until one of them is either empty or full.
Checking Validity:
For each generated state, check if it has been visited. If not, add it to visited, record its
parent state in path, and enqueue it for further exploration.
Step 3: Completion:
If the BFS completes without finding a solution (queue becomes empty), return None.
Coding:
Output:
Solution found: [(0, 0), (0, 3), (3, 0), (3, 3), (4, 2)]
Result :
Aim:
Algorithm:
Coding:
punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~'''
my_str = "Hi!!!, Welcome to ---Islamiah @#) College."
# To take input from the user
# my_str = input("Enter a string: ")
# remove punctuation from the string
no_punctuations = ""
for char in my_str:
if char not in punctuations:
no_punctuations = no_punctuations + char
print(“original string: “,my_str)
print(“without punctuations: “,no_puntuations)
Output:
Result :
Hence the program is executed and the output is verified.
4.Write a python program to sort the sentence in alphabetical order?
Aim:
To Write a python program to sort the sentence in alphabetical order
Algorithm :
Coding:
import string
def preprocess_sentence(sentence):
sentence = sentence.lower()
sentence = sentence.translate(str.maketrans('', '', string.punctuation))
return sentence
def sort_sentence(sentence):
sentence = preprocess_sentence(sentence)
words = sentence.split()
words.sort()
sorted_sentence = ' '.join(words)
return sorted_sentence
def main():
sentence = input("Enter a sentence: ")
sorted_sentence = sort_sentence(sentence)
print("\nOriginal sentence: ", sentence)
print("Sorted sentence: ", sorted_sentence)
if __name__ == "__main__":
main()
Output:
Result :
Hence the program is executed and the output is verified.
5.Write a program to implement Hangman game using python
Aim:
To Write a program to implement Hangman game using python
Algorithm:
Coding:
import random
name = input("What is your name? ")
print("Good Luck!", name)
print("Guess the computer parts!!!")
words = ['keyboard', 'mouse', 'monitor', 'printer', 'joystick', 'projector']
word = random.choice(words)
guesses = ''
turns = 7
while turns > 0:
failed = 0
for char in word:
if char in guesses:
print(char, end=" ")
else:
print("_", end=" ")
failed += 1
print()
if failed == 0:
print("You Win!")
print("The word is:", word)
break
guess = input("Guess a character: ")
guesses += guess
if guess not in word:
turns -= 1 # Reduce the number of turns left
print("Wrong guess!")
print("You have", turns, "more guesses")
if turns == 0:
print("You Lose!")
print("The word was:", word)
Output 1:
Result :
Hence the program is executed and the output is verified.
6.Write a program to implement Tic-Tac-Toe game using python.
Aim:
To Write a program to implement Tic-Tac-Toe game using python.
Algorithm:
Step 1: Initialize the Board:
Create a 3x3 board filled with spaces to represent empty cells.
Step 2: Print Board:
Define a function print_board(board) to display the current state of the board.
Step 3: Check Win Condition:
Define a function check_win(board, player) to check if a player has won by comparing all possible
winning combinations.
Step 5:Check Draw Condition:
Define a function check_draw(board) to check if the board is full and there are no empty cells left,
resulting in a draw.
Step 6: Minimax Algorithm:
Define a recursive function minimax(board, depth, is_maximizing) to evaluate the best possible
move for the AI using the Minimax algorithm:
o If the AI wins, return a score of 1.
o If the human wins, return a score of -1.
o If the game is a draw, return a score of 0.
o If it's the AI's turn (maximizing player), loop through all possible moves, place 'O', call
minimax recursively, undo the move, and return the maximum score.
o If it's the human's turn (minimizing player), loop through all possible moves, place 'X', call
minimax recursively, undo the move, and return the minimum score.
Step 7: Best Move for AI:
Define a function best_move(board) to determine the best possible move for the AI using the
minimax function:
o Loop through all possible moves, place 'O', call minimax to evaluate the move, undo the
move, and keep track of the move with the highest score.
Step 8: Main Game Loop:
Define a function play_game() to handle the game flow:
o Print the initial empty board.
o While the game is ongoing:
Human Player's Turn:
Prompt the human player to enter their move (row and column).
If the move is valid, place an 'X' on the board and print the updated board.
Check if the human player has won or if the game is a draw.
AI's Turn:
Determine the best move for the AI using best_move(board), place an 'O' on
the board, and print the updated board.
Check if the AI has won or if the game is a draw.
Step 9: Play the Game:
Call the play_game() function to start the game.
Coding:
import math
def print_board(board):
print(" | ".join(row))
print("-" * 9)
win_states = [
return True
return False
def check_draw(board):
return False
return True
if check_win(board, "O"):
return 1
elif check_draw(board):
return 0
if is_maximizing:
best_score = -math.inf
for i in range(3):
for j in range(3):
board[i][j] = "O"
return best_score
else:
best_score = math.inf
for i in range(3):
for j in range(3):
board[i][j] = "X"
return best_score
def best_move(board):
best_score = -math.inf
move = (0, 0)
for i in range(3):
for j in range(3):
board[i][j] = "O"
score = minimax(board, 0, False)
best_score = score
move = (i, j)
return move
def play_game():
print_board(board)
while True:
row, col = map(int, input("Enter your move (row and column): ").split())
board[row][col] = "X"
else:
continue
print_board(board)
if check_win(board, "X"):
print("You win!")
break
elif check_draw(board):
print("It's a draw!")
break
# AI's turn
board[ai_row][ai_col] = "O"
print_board(board)
if check_win(board, "O"):
print("AI wins!")
break
elif check_draw(board):
print("It's a draw!")
break
play_game()
Output 1:
| |
---------
| |
---------
| |
AI wins!
Output 2:
| |
---------
| |
---------
| |
Enter your move (row and column): 0 0
X| |
---------
| |
---------
| |
---------
X|O|
---------
| |
---------
| |
It's a draw!
Result :
Hence the program is executed and the output is verified.
7. Write a python program to remove stop words for a given passage from a text file using NLTK?
Aim:
To Write a python program to remove stop words for a given passage from a text file using NLTK
Algorithm:
Coding:
import nltk
nltk.download('stopwords')
nltk.download('punkt')
def remove_stopwords(text):
words = word_tokenize(text)
stop_words = set(stopwords.words('english'))
def main():
text = file.read()
cleaned_text = remove_stopwords(text)
print("Original Text:")
print(text)
print(cleaned_text)
if __name__ == "__main__":
main()
Output:
Original Text:
This is an example sentence demonstrating the removal of stopwords from text.
Result :
Hence the program is executed and the output is verified.
8.Write a python program to implement stemming for a given sentence using NLTK?
Aim:
To Write a python program to implement stemming for a given sentence using NLTK
Algorithm:
Coding:
import nltk
nltk.download('punkt')
def stem_sentence(sentence):
words = word_tokenize(sentence)
porter = PorterStemmer()
return stemmed_sentence
stemmed_sentence = stem_sentence(sentence)
Output:
Result :
Hence the program is executed and the output is verified.
9.Write a python program to POS (Parts of Speech) tagging for the give sentence using NLTK?
Aim:
To Write a python program to POS (Parts of Speech) tagging for the give sentence using NLTK
Algorithm:
o Import the Natural Language Toolkit (NLTK) library, which provides tools for natural
language processing.
o Create a string variable called sentence that contains the text you want to analyze.
o Example: sentence = "NLTK is a leading platform for building Python
programs to work with human language data."
o Use nltk.pos_tag(tokens) to assign POS tags to each token. This identifies the
grammatical category of each word (e.g., noun, verb, adjective).
o Store the POS tags in a variable (e.g., pos_tags).
o Use print(pos_tags) to display the list of tokens along with their corresponding POS
tags.
CODING:
import nltk
nltk.download('punkt')
nltk.download('averaged_perceptron_tagger')
sentence="NLTK is a leading platform form building python program to work with human
language date."
tokens=nltk.word_tokenize(sentence)
pos_tags=nltk.pos_tag(tokens)
print(pos_tags)
OUTPUT:
[('NLTK', 'NNP'), ('is', 'VBZ'), ('a', 'DT'), ('leading', 'VBG'), ('platform', 'NN'), ('form', 'NN'),
('building', 'NN'), ('python', 'NN'), ('program', 'NN'), ('to', 'TO'), ('work', 'VB'), ('with', 'IN'),
('human', 'JJ'), ('language', 'NN'), ('date', 'NN'), ('.', '.')]
RESULT :
Aim:
To write a python program to implement Lemmatization using NLTK
Alogrithm:
o Import necessary components from the NLTK library such as WordNetLemmatizer and
word_tokenize.
o Download the wordnet and punkt resources, which are essential for lemmatization and
tokenization respectively.
o Define the text to be processed. In this case: "The foxes are quick and they're jumping
over the sleeping dogs".
o Split the input text into individual words using the word_tokenize function. This breaks
the text into tokens (words and punctuation marks).
o Apply the lemmatize() method from the WordNetLemmatizer to each token (word) in
the list. This method looks up the base form (lemma) of each word. By default, it treats
every word as a noun unless otherwise specified.
o After lemmatizing the tokens, the processed words are joined back into a single string
with spaces between them.
o Print the original and lemmatized versions of the text for comparison.
Coding:
import nltk
nltk.download('wordnet')
nltk.download('punkt')
text = "The children are playing outside .They enjoy their games and laugh together. Each
words = word_tokenize(text)
lemmatizer = WordNetLemmatizer()
print("Original text:")
print(text)
print("\nLemmatized text:")
print(lemmatized_text)
Output:
Original Text:
The children are playing outside .They enjoy their games and laugh together. Each child has a
unique talent
Lemmatized Text:
The child are playing outside .They enjoy their game and laugh together. Each child ha a unique
talent
Result :
Aim:
To Write a python program to for Text Classification for the give sentence using NLTK
Algorithm :
o Import necessary modules from NLTK (Natural Language Toolkit) like tokenize,
NaiveBayesClassifier, and stopwords.
o Download required datasets from NLTK, such as word tokenizers (punkt) and English
stopwords (stopwords).
o Prepare a small set of labeled sentences (training data) where each sentence is either
"positive" or "negative".
o Apply the preprocess function to each sentence in the training data, transforming them
into a format suitable for the classifier.
o Print the classified label (either "positive" or "negative") for the test sentence.
CODING :
import nltk
from nltk.tokenize import word_tokenize
from nltk.classify import NaiveBayesClassifier
from nltk.corpus import stopwords
import string
# Test sentence
test_sentence = "I love this amazing weather"
OUTPUT:
The sentence is classified as: positive
RESULT :
Hence the program is executed and the output is verified.