FINALailabfile
FINALailabfile
(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
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
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
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
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
# 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
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
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.
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
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.
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."
tokenized = sent_tokenize(txt)
for i in tokenized:
print(tagged)
print("\n Name : NIHAL KUMAR")
print("Roll No. : 2201921530109")
print("Class : CSAIML-2")
Program No - 10
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
# Example sentences
sentence = "I love this movie! It was amazing and fun."
print(f"Sentence: {sentence}")
print("Classification:", classify_sentence(sentence))