0% found this document useful (0 votes)
26 views26 pages

FINALailabfile

Uploaded by

kaifali532
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)
26 views26 pages

FINALailabfile

Uploaded by

kaifali532
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
You are on page 1/ 26

Artificial Intelligence Lab

(BCAI-551)

LAB FILE
Dept. of Computer Science & Engineering (AIML)
ACADEMIC SESSION 2024-25 (ODD SEM)
COURSE: B. TECH (CSEAIML)
SEM: Vth
Submitted to: Submitted by:
Mr. Gaurav Dhuriya Name: NIHAL KUMAR
Roll. No.:2201921530109
Class: CSAIML-2

G. L. BAJAJ INSTITUTE OF TECHNOLOGY AND MANAGEMENT


Plot no. 2, Knowledge Park III, Gr. Noida
S. EXPERIMENTS DATE FACULTY REMARKS
NO. SIGN.
Program No - 1

Objective: Write a python program to implement Breadth First Search


Traversal in Python.

1. Breadth First Search Traversal


Breadth First Search (BFS) is a fundamental graph traversal algorithm. It begins
with a node, then first traverses all its adjacent. Once all adjacent are visited,
then their adjacent are traversed. This is different from DFS in a way that closest
vertices are visited before others. We mainly traverse vertices level by level. A
lot of popular graph algorithms like Dijkstra’s shortest path, Kahn’s Algorithm,
and Prim’s algorithm are based on BFS. BFS itself can be used to detect cycle in
a directed and undirected graph, find shortest path in an unweighted graph and
many more problems.

Code:
from collections import deque
# BFS from given source s
def bfs(adj, s):
# Create a queue for BFS
q = deque()
# Initially mark all the vertices as not visited
# When we push a vertex into the q, we mark it as
# visited
visited = [False] * len(adj);
# Mark the source node as visited and enqueue it
visited[s] = True
q.append(s)
# Iterate over the queue
while q:
# Dequeue a vertex from queue and print it
curr = q.popleft()
print(curr, end=" ")
# Get all adjacent vertices of the dequeued
# vertex. If an adjacent has not been visited,
# mark it visited and enqueue it
for x in adj[curr]:
if not visited[x]:
visited[x] = True
q.append(x)
# Function to add an edge to the graph
def add_edge(adj, u, v):
adj[u].append(v)
adj[v].append(u)

# Example usage
if __name__ == "__main__":
# Number of vertices in the graph
V=5
# Adjacency list representation of the graph
adj = [[] for _ in range(V)]
# Add edges to the graph
add_edge(adj, 0, 1)
add_edge(adj, 0, 2)
add_edge(adj, 1, 3)
add_edge(adj, 1, 4)
add_edge(adj, 2, 4)
# Perform BFS traversal starting from vertex 0
print("BFS starting from 0: ")
bfs(adj, 0)
print("\nName : NIHAL KUMAR")
print("Roll No. : 2201921530109")
print("Class : CSAIML-2")
Program No – 2

Objective: Write a python program to implement Water Jug Problem.

Water Jug Problem


Given two empty jugs of m and n litres respectively. The jugs don’t have
markings to allow measuring smaller quantities. You have to use the jugs to
measure d litres of water. The task is to find the minimum number of
operations to be performed to obtain d litres of water in one of the jugs. In
case of no solution exist, return -1.
The operations you can perform are:
• Empty a Jug
• Fill a Jug
• Pour water from one jug to the other until one of the jugs is either
empty or full.

Code:
from collections import deque
# Function to find the minimum operations to obtain
# d liters in one jug
def min_steps(m, n, d):
if d > max(m, n):
return -1
# Queue for BFS: (jug1, jug2, steps)
q = deque([(0, 0, 0)])
# For tracking the visited states
visited = [[False] * (n + 1) for _ in range(m + 1)]
visited[0][0] = True
while q:
jug1, jug2, steps = q.popleft()
if jug1 == d or jug2 == d:
return steps
# 1: Fill jug1
if not visited[m][jug2]:
visited[m][jug2] = True
q.append((m, jug2, steps + 1))
# 2: Fill jug2
if not visited[jug1][n]:
visited[jug1][n] = True
q.append((jug1, n, steps + 1))
# 3: Empty jug1
if not visited[0][jug2]:
visited[0][jug2] = True
q.append((0, jug2, steps + 1))
# 4: Empty jug2
if not visited[jug1][0]:
visited[jug1][0] = True
q.append((jug1, 0, steps + 1))
# 5: Pour jug1 into jug2
pour1to2 = min(jug1, n - jug2)
if not visited[jug1 - pour1to2][jug2 + pour1to2]:
visited[jug1 - pour1to2][jug2 + pour1to2] = True
q.append((jug1 - pour1to2, jug2 + pour1to2, steps + 1))
# 6: Pour jug2 into jug1
pour2to1 = min(jug2, m - jug1)
if not visited[jug1 + pour2to1][jug2 - pour2to1]:
visited[jug1 + pour2to1][jug2 - pour2to1] = True
q.append((jug1 + pour2to1, jug2 - pour2to1, steps + 1))
return -1
if __name__ == "__main__":
# jug1 = 4 litre, jug2 = 3 litre
m, n, d = 4, 3, 2
print(min_steps(m, n, d))
print("\n Name : NIHAL KUMAR")
print("Roll No. : 2201921530109")
print("Class : CSAIML-2")
Program No – 3

Objective: Write a python program to remove punctuations from the given


string.

Theory:
Many times while working with Python strings, we have a problem in which we
need to remove certain characters from strings. This can have applications in
data preprocessing in the Data Science domain and also in day-to-day
programming. Let’s discuss certain ways in which we can perform this task
using Python.

Code:
import string
test_str = 'Gfg, is best: for ! Geeks ;'
test_str = test_str.translate(str.maketrans('', '', string.punctuation))
print(test_str)
print("\n Name : NIHAL KUMAR")
print("Roll No. : 2201921530109")
print("Class : CSAIML-2")
Program No – 4

Objective: Write a python program to sort the sentence in alphabetical order.

Theory:
Python sorted() is a predefined function in Python that returns the sorted list
of any particular sequence.

Code:
# Python3 program to sort the words of a string in
# alphabetical order

# Function to sort the words in alphabetical order


def Func(S):
W = S.split(" ")
for i in range(len(W)):

# convert all the words into lowercase


W[i]=W[i].lower()
S = sorted(W)
print(' '.join(S))

# Driver code
S = "the Quick brown fox jumPs over the lazY Dog"

# function call
Func(S)
print("\n Name : NIHAL KUMAR")
print("Roll No. : 2201921530109")
print("Class : CSAIML-2")
Program No – 5

Objective: Write a program to implement Hangman game using python.

Theory:
Hangman is a word game in which the computer will randomly select a word
from the dictionary and the player has to guess it correctly in a given number of
turns. The word to be guessed is represented by the row of stars. If the guessed
letter is present in a word, the script will automatically be placed in the correct
places.

Code:
import random
name = input("What is your name? ")
print("Good Luck ! ", name)
words = ['rainbow', 'computer', 'science', 'programming',
'python', 'mathematics', 'player', 'condition',
'reverse', 'water', 'board', 'geek']
word = random.choice(words)
print("Guess the characters")
guesses = ''
turns = 1
while turns > 0:
failed = 0
for char in word:
if char in guesses:
print(char, end=" ")
else:
print("_")
failed += 1
if failed == 0:
print("You Win")
print("The word is: ", word)
break
print()
guess = input("guess a character:")
guesses += guess
if guess not in word:
turns -= 1
print("Wrong")
print("You have", + turns, 'more guesses')
if turns == 0:
print("You Loose")
print("\n Name : NIHAL KUMAR")
print("Roll No. : 2201921530109")
print("Class : CSAIML-2")
Program No – 6

Objective: Write a program to implement Tic-Tac-Toe game using python.

Tic-Tac-Toe Game:
Tic-Tac-Toe is among the games played between two players played on a 3 x 3
square grid. Each player inhabits a cell in their respective turns, keeping the
objective of placing three similar marks in a vertical, horizontal, or diagonal
pattern. The first player utilizes the Cross (X) as the marker, whereas the other
utilizes the Naught or Zero (O).

Code:
import random
import time
# Constants for the game
COMPUTER = 1
HUMAN = 2
SIDE = 3
COMPUTERMOVE = 'O'
HUMANMOVE = 'X'
# Function to initialise the game / Tic-Tac-Toe board
def initialise():
board = [[' ' for _ in range(SIDE)] for _ in range(SIDE)]
moves = [i for i in range(SIDE*SIDE)]
random.shuffle(moves)
return board, moves
# Function to print the Tic-Tac-Toe board
def showBoard(board):
print("\n\n")
print("\t\t\t {} | {} | {} ".format(board[0][0], board[0][1], board[0][2]))
print("\t\t\t--------------")
print("\t\t\t {} | {} | {} ".format(board[1][0], board[1][1], board[1][2]))
print("\t\t\t--------------")
print("\t\t\t {} | {} | {} \n\n".format(board[2][0], board[2][1], board[2][2]))
# Function to show the instructions
def showInstructions():
print("\t\t\t Tic-Tac-Toe\n\n")
print("Choose a cell numbered from 1 to 9 as below and play\n\n")
print("\t\t\t 1 | 2 | 3 ")
print("\t\t\t--------------")
print("\t\t\t 4 | 5 | 6 ")
print("\t\t\t--------------")
print("\t\t\t 7 | 8 | 9 \n\n")
print("-\t-\t-\t-\t-\t-\t-\t-\t-\t-\n\n")
# Function to declare the winner of the game
def declareWinner(whoseTurn):
if whoseTurn == COMPUTER:
print("COMPUTER has won")
else:
print("HUMAN has won")
# Functions to check if any of the rows, columns, or diagonals have been
crossed
def rowCrossed(board):
for i in range(SIDE):
if board[i][0] == board[i][1] and board[i][1] == board[i][2] and board[i][0]
!= ' ':
return True
return False
def columnCrossed(board):
for i in range(SIDE):
if board[0][i] == board[1][i] and board[1][i] == board[2][i] and board[0][i]
!= ' ':
return True
return False
def diagonalCrossed(board):
if board[0][0] == board[1][1] and board[1][1] == board[2][2] and board[0][0]
!= ' ':
return True
if board[0][2] == board[1][1] and board[1][1] == board[2][0] and board[0][2]
!= ' ':
return True
return False
# Function to check if the game is over
def gameOver(board):
return rowCrossed(board) or columnCrossed(board) or
diagonalCrossed(board)
# Function to play Tic-Tac-Toe
def playTicTacToe(whoseTurn):
board, moves = initialise()
showInstructions()
moveIndex = 0
while not gameOver(board) and moveIndex != SIDE*SIDE:
if whoseTurn == COMPUTER:
x = moves[moveIndex] // SIDE
y = moves[moveIndex] % SIDE
board[x][y] = COMPUTERMOVE
print("COMPUTER has put a {} in cell {}".format(COMPUTERMOVE,
moves[moveIndex]+1))
showBoard(board)
moveIndex += 1
whoseTurn = HUMAN
elif whoseTurn == HUMAN:
x = moves[moveIndex] // SIDE
y = moves[moveIndex] % SIDE
board[x][y] = HUMANMOVE
print("HUMAN has put a {} in cell {}".format(HUMANMOVE,
moves[moveIndex]+1))
showBoard(board)
moveIndex += 1
whoseTurn = COMPUTER
if not gameOver(board) and moveIndex == SIDE*SIDE:
print("It's a draw")
else:
if whoseTurn == COMPUTER:
whoseTurn = HUMAN
elif whoseTurn == HUMAN:
whoseTurn = COMPUTER
declareWinner(whoseTurn)
# Driver function
if __name__ == "__main__":
# Let us play the game with COMPUTER starting first
playTicTacToe(COMPUTER)
print("\n Name : NIHAL KUMAR")
print("Roll No. : 2201921530109")
print("Class : CSAIML-2")
Program No - 7

Objective: Write a python program to remove stop words for a given passage
from a text file using NLTK.

Removing stop words with NLTK in Python:


In natural language processing (NLP), stopwords are frequently filtered out to
enhance text analysis and computational efficiency. Eliminating stopwords can
improve the accuracy and relevance of NLP tasks by drawing attention to the
more important words, or content words. The article aims to explore stopwords.

Code:
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
example_sent = """This is a sample sentence,
showing off the stop words filtration."""
stop_words = set(stopwords.words('english'))
word_tokens = word_tokenize(example_sent)

# converts the words in word_tokens to lower case and then checks whether
#they are present in stop_words or not

filtered_sentence = [w for w in word_tokens if not w.lower() in stop_words]


#with no lower case conversion
filtered_sentence = []
for w in word_tokens:
if w not in stop_words:
filtered_sentence.append(w)
print(word_tokens)
print(filtered_sentence)
print("\n Name : NIHAL KUMAR")
print("Roll No. : 2201921530109")
print("Class : CSAIML-2")
Program No - 8

Objective: Write a python program to implement stemming for a given


sentence using NLTK.

Stemming words with NLTK:


Stemming is the process of producing morphological variants of a root/base
word. Stemming programs are commonly referred to as stemming algorithms or
stemmers. A stemming algorithm reduces the words “chocolates”, “chocolatey”,
and “choco” to the root word, “chocolate” and “retrieval”, “retrieved”,
“retrieves” reduce to the stem “retrieve”.

Code:
# import these modules
from nltk.stem import PorterStemmer
from nltk.tokenize import word_tokenize
ps = PorterStemmer()
# choose some words to be stemmed
words = ["program", "programs", "programmer", "programming",
"programmers"]
for w in words:
print(w, " : ", ps.stem(w))
print("\n Name : NIHAL KUMAR")
print("Roll No. : 2201921530109")
print("Class : CSAIML-2")
Program No - 9

Objective: Write a python program to POS (Parts of Speech) tagging for the
given sentence using NLTK.

Part of Speech Tagging with Stop words using NLTK:


The Natural Language Toolkit (NLTK) is a platform used for building programs
for text analysis. One of the more powerful aspects of the NLTK module is the
Part of Speech tagging.

Code:
import nltk
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize, sent_tokenize
stop_words = set(stopwords.words('english'))

// Dummy text
txt = "Sukanya, Rajib and Naba are my good friends. " \
"Sukanya is getting married next year. " \
"Marriage is a big step in one’s life." \
"It is both exciting and frightening. " \
"But friendship is a sacred bond between people." \
"It is a special kind of love between us. " \
"Many of you must have tried searching for a friend "\
"but never found the right one."

# sent_tokenize is one of instances of


# PunktSentenceTokenizer from the nltk.tokenize.punkt module

tokenized = sent_tokenize(txt)
for i in tokenized:

# Word tokenizers is used to find the words


# and punctuation in a string
wordsList = nltk.word_tokenize(i)
# removing stop words from wordList
wordsList = [w for w in wordsList if not w in stop_words]

# Using a Tagger. Which is part-of-speech


# tagger or POS-tagger.
tagged = nltk.pos_tag(wordsList)

print(tagged)
print("\n Name : NIHAL KUMAR")
print("Roll No. : 2201921530109")
print("Class : CSAIML-2")
Program No - 10

Objective: Write a python program to implement Lemmatization using NLTK.

Lemmatization with NLTK:


Lemmatization is a fundamental text pre-processing technique widely applied
in natural language processing (NLP) and machine learning. Serving a purpose
akin to stemming, lemmatization seeks to distill words to their foundational
forms. In this linguistic refinement, the resultant base word is referred to as a
“lemma.” The article aims to explore the use of lemmatization and demonstrates
how to perform lemmatization with NLTK.

Code:
# import these modules
from nltk.stem import WordNetLemmatizer
lemmatizer = WordNetLemmatizer()
print("rocks :", lemmatizer.lemmatize("rocks"))
print("corpora :", lemmatizer.lemmatize("corpora"))
# a denotes adjective in "pos"
print("better :", lemmatizer.lemmatize("better", pos="a"))
print("\n Name : NIHAL KUMAR")
print("Roll No. : 2201921530109")
print("Class : CSAIML-2")
Program No - 11

Objective: Write a python program to for Text Classification for the give
sentence using NLTK.

Code:
import nltk
from nltk.corpus import movie_reviews
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
from nltk.classify import NaiveBayesClassifier
from nltk.probability import FreqDist
import random

# Ensure necessary NLTK data is downloaded


nltk.download('movie_reviews')
nltk.download('punkt')
nltk.download('stopwords')

# Preprocess and extract features from text


def extract_features(words):
stop_words = set(stopwords.words('english'))
words_filtered = [word for word in words if word.lower() not in stop_words]
word_features = FreqDist(words_filtered)
return {word: True for word in word_features}

# Prepare the dataset


positive_reviews = [(extract_features(movie_reviews.words(fileid)), 'pos')
for fileid in movie_reviews.fileids('pos')]

negative_reviews = [(extract_features(movie_reviews.words(fileid)), 'neg')


for fileid in movie_reviews.fileids('neg')]

# Shuffle the data to ensure randomness


reviews = positive_reviews + negative_reviews
random.shuffle(reviews)

# Split the data into training and testing sets


train_set = reviews[:1500]
test_set = reviews[1500:]

# Train a Naive Bayes classifier


classifier = NaiveBayesClassifier.train(train_set)

# Define a function to classify a given sentence


def classify_sentence(sentence):
words = word_tokenize(sentence)
features = extract_features(words)
return classifier.classify(features)

# Example sentences
sentence = "I love this movie! It was amazing and fun."
print(f"Sentence: {sentence}")
print("Classification:", classify_sentence(sentence))

sentence = "This movie was terrible. I hated it."


print(f"Sentence: {sentence}")
print("Classification:", classify_sentence(sentence))
print("\n Name : NIHAL KUMAR")
print("Roll No. : 2201921530109")
print("Class : CSAIML-2")

You might also like