0% found this document useful (0 votes)
2 views

Lab File Complete

The document contains a series of Python programs that implement various algorithms and functionalities, including breadth-first search traversal, punctuation removal, sentence sorting, and a water jug problem solver. It also includes programs for removing stop words using NLTK, text classification, parts of speech tagging, and a hangman game. Each program is accompanied by its code and expected output.

Uploaded by

harshdixit1290
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Lab File Complete

The document contains a series of Python programs that implement various algorithms and functionalities, including breadth-first search traversal, punctuation removal, sentence sorting, and a water jug problem solver. It also includes programs for removing stop words using NLTK, text classification, parts of speech tagging, and a hangman game. Each program is accompanied by its code and expected output.

Uploaded by

harshdixit1290
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

INDEX

S NO. PROGRAM DATE SIGN


PYTHON PROGRAM TO IMPLEMENT BREADTH FIRST
1.
SEARCH TRAVERSAL.
30/09/24
PYTHON PROGRAM TO REMOVE PUNCTUATIONS
2.
FROM THE GIVEN STRING
07/10/24
PYTHON PROGRAM TO SORT THE SENTENCE IN
3.
ALPHABETICAL ORDER
18/10/24
PYTHON PROGRAM TO IMPLEMENT WATER JUG
4.
PROBLEM
18/10/24
PYTHON PROGRAM TO REMOVE STOP WORDS FOR A
5.
GIVEN PASSAGE FROM A TEXT FILE USING NLTK
25/10/24
PYTHON PROGRAM TO FOR TEXT CLASSIFICATION
6.
FOR THE GIVE SENTENCE USING NLTK
15/11/24
PYTHON PROGRAM TO POS (PARTS OF SPEECH)
7.
TAGGING FOR THE GIVE SENTENCE USING NLTK
22/11/24
PROGRAM TO IMPLEMENT HANGMAN GAME USING
8.
PYTHON
06/12/24

1|Page
PROGRAM 1

PYTHON PROGRAM TO IMPLEMENT BREADTH FIRST SEARCH TRAVERSAL


from collections import defaultdict
# this class represents a directed graph using adjacency list representation
class graph:
def __init__(self): # constructor
self.graph = defaultdict(list)
# default dictionary to store graph function to add an edge to graph
def addedge(self, u, v):
self.graph[u].append(v)
# function to print a bfs of graph
def bfs(self, s):
# mark all the vertices as not visited
visited = [false] * (max(self.graph) + 1)
# create a queue for bfs
queue = []
# mark the source node as visited and enqueue it
queue.append(s)
visited[s] = true
while queue:
# dequeue a vertex from queue and print it
s = queue.pop(0)
print(s, end=" ")
# get all adjacent vertices of the dequeued vertex s. if an adjacent
#has not been visited, then mark it visited and enqueue it
for i in self.graph[s]:
if not visited[i]:
queue.append(i)
visited[i] = true

if __name__ == '__main__':

# create a graph given in the above diagram


g = graph()
g.addedge(0, 1)
g.addedge(0, 2)
g.addedge(1, 2)
g.addedge(2, 0)
g.addedge(2, 3)
g.addedge(3, 3)

print("following is breadth first traversal (starting from vertex 2)")


g.bfs(2)
Output-
Following is Breadth First Traversal (starting from vertex 2)
2031

2|Page
PROGRAM 2

PYTHON PROGRAM TO REMOVE PUNCTUATIONS FROM THE GIVEN STRING

import re

# initializing string
test_str = "KCNIT, is best : for ! students ;"

# printing original string


print("the original string is : " + test_str)

# removing punctuations in string


# using regex
res = re.sub(r'[^\w\s]', '', test_str)

# printing result
print("the string after punctuation filter : " + res)

Output-
The original string is : KCNIT, is best : for ! students ;
The string after punctuation filter : KCNIT is best for students

3|Page
PROGRAM 3

PYTHON PROGRAM TO SORT THE SENTENCE IN ALPHABETICAL ORDER

# To take input from the user


my_str = input("Enter a string: ")

# breakdown the string into a list of words


words = [word.lower() for word in my_str.split()]

# sort the list


words.sort()

# display the sorted words

print("The sorted words are:")


for word in words:
print(word)

4|Page
PROGRAM 4

PYTHON PROGRAM TO IMPLEMENT WATER JUG PROBLEM

# this function is used to initialize the dictionary elements with a #default value.
from collections import defaultdict

# jug1 and jug2 contain the value for max capacity in respective jugs
# and aim is the amount of water to be measured.
jug1, jug2, aim = 4, 3, 2
# initialize dictionary with default value as false.
visited = defaultdict(lambda: false)

# recursive function which prints the intermediate steps to reach the final solution and return boolean
# value (true if solution is# possible, otherwise false). amt1 and amt2 are the amount of
# water present in both jugs at a certain point of time.

def waterjugsolver(amt1, amt2):


# checks for our goal and returns true if achieved.
if (amt1 == aim and amt2 == 0) or (amt2 == aim and amt1 == 0):
print(amt1, amt2)
return true
# checks if we have already visited the
# combination or not. if not, then it proceeds further.
if visited[(amt1, amt2)] == false:
print(amt1, amt2)
# changes the boolean value of the combination as it is visited.
visited[(amt1, amt2)] = true
# check for all the 6 possibilities and
# see if a solution is found in any one of them.
return (waterjugsolver(0, amt2) or
waterjugsolver(amt1, 0) or
waterjugsolver(jug1, amt2) or
waterjugsolver(amt1, jug2) or
waterjugsolver(amt1 + min(amt2, (jug1-amt1)),
amt2 - min(amt2, (jug1-amt1))) or
waterjugsolver(amt1 - min(amt1, (jug2-amt2)),
amt2 + min(amt1, (jug2-amt2))))
# return false if the combination is
# already visited to avoid repetition otherwise
# recursion will enter an infinite loop.
else:
return false
print("steps: ")
# call the function and pass the
# initial amount of water present in both jugs.
waterjugsolver(0, 0)

5|Page
PROGRAM 5

PYTHON PROGRAM TO REMOVE STOP WORDS FOR A GIVEN PASSAGE FROM


A TEXT FILE USING NLTK

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)

Output:
['This', 'is', 'a', 'sample', 'sentence', ',', 'showing',
'off', 'the', 'stop', 'words', 'filtration', '.']
['This', 'sample', 'sentence', ',', 'showing', 'stop',
'words', 'filtration', '.']

6|Page
PROGRAM 6

PYTHON PROGRAM TO FOR TEXT CLASSIFICATION FOR THE GIVE


SENTENCE USING NLTK
from nltk import pos_tag
from nltk import word_tokenize

text = "KCNIT is a computer science platform."


tokenized_text = word_tokenize(text)
tags = tokens_tag = pos_tag(tokenized_text)
tags

Output:
[(KCNIT, 'NNP'),
('is', 'VBZ'),
('a', 'DT'),
('Computer', 'NNP'),
('Science', 'NNP'),
('platform', 'NN'),
('.', '.')]

7|Page
PROGRAM 7

PYTHON PROGRAM TO POS (PARTS OF SPEECH) TAGGING FOR THE GIVE


SENTENCE USING NLTK

# importing the nltk library


import nltk
from nltk.tokenize import word_tokenize
from nltk import pos_tag

# sample text
text = "nltk is a powerful library for natural language processing."

# performing pos tagging


pos_tags = pos_tag(words)

# displaying the pos tagged result in separate lines


print("original text:")
print(text)

print("\npos tagging result:")


for word, pos_tag in pos_tags:
print(f"{word}: {pos_tag}")

Output:
Original Text:
NLTK is a powerful library for natural language processing.
PoS Tagging Result:
NLTK: NNP
is: VBZ
a: DT
powerful: JJ
library: NN
for: IN
natural: JJ
language: NN
processing: NN
.: .

8|Page
PROGRAM 8

PROGRAM TO IMPLEMENT HANGMAN GAME USING PYTHON

import random
import words

# Function to randomly select a word from dictionary


def get_word():
# Path to the text file
with open('/GeeksforGeeks/Hangman/words.txt', 'r') as f:
# Reads each word after splitting
words1 = f.read().splitlines()
# Returns any random word
return random.choice(words1)

def hangman():
# randomly chose a word form the list of words.
chosen_word = get_word()
# keep an empty list that is used to display the letters
# and empty spaces in a word that user must guess.
display = []
for _ in chosen_word:
display += "_"

# the initial game variables setup.


# Set the lives and variable that keeps track of loop that runs
# the game
end_of_loop = False
lives = 6

# display a welcoming message for the user.


print("\n-------------Welcome to Hangman-------------\n")
print("Guess the word:- ", end=" ")
print(f"{' '.join(display)}")
print(f"Lives: {lives}")

while not end_of_loop:


guess = input("Guess a Letter: ").lower()
# reduce the lives if the guessed letter does not exist in the
# word that user has to guess
if not (guess in chosen_word):
lives -= 1
# now replace empty space of word with guessed letter if the
# user guessed a letter that is in the word.
index = 0
for c in chosen_word:

9|Page
if c == guess:
display[index] = guess
index += 1

# Again display the status of game.


print(f"{' '.join(display)}")
print(f"Lives: {lives}")
print(stages[lives-1])

# check of there are no _ in the display list, then that means


# the user has guessed all the letters correctly.
if "_" not in display:
print("You Win")
end_of_loop = True

# check if he has run out of lives, then he has lost the game.
if lives == 0:
print("You Lose")
print(f"The word was: {chosen_word}")
end_of_loop = True

# The loop that will keep calling the game play function again and again unless the user does not want
#to play it anymore.
end_of_game = False
while not end_of_game:
# ask user if he wants to play the game
ask = input("Do you want to play Hangman? (y/n): ").lower()
# if he insert yes, then call the function for playing the game.
if ask == 'y' or ask == 'yes':
hangman()
# if the answer is no, quit the loop and end the program.
elif ask == 'n' or ask == 'no':
print("Program Exit Successful")
end_of_game = True
# if the user entered something else, ask again.
else:
print("Your given input could not be processed.")
print("Please enter a correct input.")

10 | P a g e

You might also like