0% found this document useful (0 votes)
6 views22 pages

Python Graph and Text Processing Algorithms

The document outlines multiple Python programming experiments, each with specific objectives, algorithms, and sample codes. Key topics include graph traversal using Breadth First Search, solving the Water Jug Problem, cleaning strings by removing punctuation, sorting sentences, and implementing games like Hangman and Tic-Tac-Toe. Additionally, it covers natural language processing tasks such as stemming, lemmatization, POS tagging, and text classification using NLTK.

Uploaded by

himeshkhare132
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)
6 views22 pages

Python Graph and Text Processing Algorithms

The document outlines multiple Python programming experiments, each with specific objectives, algorithms, and sample codes. Key topics include graph traversal using Breadth First Search, solving the Water Jug Problem, cleaning strings by removing punctuation, sorting sentences, and implementing games like Hangman and Tic-Tac-Toe. Additionally, it covers natural language processing tasks such as stemming, lemmatization, POS tagging, and text classification using NLTK.

Uploaded by

himeshkhare132
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

Experiment No.

Write a python program to implement Breadth First Search Traversal.


Objective:
To explore a graph level-by-level starting from a selected node. BFS visits all neighbors first
before moving deeper.

Sample Input:
Graph = { 'A': ['B','C'], 'B':['D','E'], 'C':['F'], 'D':[], 'E':[], 'F':[] }
Start = A

Expected Output:
ABCDEF

Algorithm:

1. Create a queue and add the start node.


2. Mark the node as visited.
3. Remove one node from queue → print it.
4. Add all its unvisited neighbours.
5. Repeat until queue becomes empty.

Python Code:
from collections import deque

graph = {
'A': ['B','C'],
'B': ['D','E'],
'C': ['F'],
'D': [],
'E': [],
'F': []
}

def bfs(start):
q = deque([start])
visited = set()

while q:
node = [Link]()
if node not in visited:
print(node, end=" ")
[Link](node)
for n in graph[node]:
[Link](n)

print("BFS Traversal:")
bfs('A')

Output:

Output Analysis:
The algorithm first visits A, then its neighbors B and C, then the deeper levels D, E, and F.
Experiment No. 2
Write a python program to implement Water Jug Problem.
Objective:
To measure an exact amount of water using two jugs of different capacities using operations
like fill, empty, and transfer. To measure an exact amount of water using two jugs of fixed
sizes. We try all valid operations:
→ Fill jug, Empty jug, Pour from one jug to another.
We explore all possible states until we get the target amount.

Sample Input:
Jug1 = 4L, Jug2 = 3L
Target = 2L

Expected Output:.

A sequence of jug states leading to amount = 2.

Algorithm:

1. Start from (0,0).


2. Use BFS to explore all states.
3. For each state, try all 6 operations.
4. Stop when one jug contains target.

Python Code:
from collections import deque
def water_jug(a, b, target):
q = deque()
used = set()
[Link]((0, 0))

while q:
x, y = [Link]()

if (x, y) in used:
continue
[Link]((x, y))

print(x, y)

if x == target or y == target:
print("Target reached")
break

[Link]((a, y)) # fill jug1


[Link]((x, b)) # fill jug2
[Link]((0, y)) # empty jug1
[Link]((x, 0)) # empty jug2

p = min(x, b - y) # pour 1->2


[Link]((x - p, y + p))

p = min(y, a - x) # pour 2->1


[Link]((x + p, y - p))

water_jug(4, 3, 2)

Output:
Output Analysis:
You finally get exactly 2 liters in Jug1.
The BFS ensures all possibilities are tried until one jug becomes 2 liters.

Fill Jug1: 4,0


Transfer Jug1->Jug2: 1,3
Empty Jug2: 1,0
Transfer Jug1->Jug2: 0,1
Fill Jug1: 4,1
Transfer Jug1->Jug2: 2,3
Experiment No. 3
Write a python program to remove punctuations from the given string.
Objective:
To clean a given string by removing symbols like ! , . ? etc. To clean a given string by
removing punctuation symbols such as ! , . ? ; :.
This makes the text suitable for processing, searching, counting words, etc.

Sample Input:
“Hello!! Welcome, to Python?”

Expected Output:
Hello Welcome to Python

Algorithm:

1. Define all punctuation characters.


2. Loop through string.
3. Add character only if it is not punctuation.

Python Code:
text = "Hello!! Welcome, to Python?"
p = "!,.?;:'-"

res = ""
for ch in text:
if ch not in p:
res += ch

print("Original:", text)
print("After:", res)
Output:

Output Analysis:

All punctuation symbols are removed and only meaningful words remain.

All unwanted punctuation marks are removed leaving a clean text.


Experiment No. 4
Write a python program to sort the sentence in alphabetical order.
Objective:
To read a sentence and print all words sorted alphabetically. To sort all words of a sentence
in alphabetical (A–Z) order.
This is useful in dictionary ordering, text mining, and searching.

Sample Input:
“python is a good language”

Expected Output:
“a good is language python”

Algorithm:

1. Split string into words.


2. Sort list of words.
3. Join and print sorted result.

Python Code:
s = "python is a good language"

words = [Link]()
[Link]()

print("Original:", s)
print("Sorted:", " ".join(words))

Output:

Output Analysis:
Words are arranged in increasing alphabetical order. The list sorts alphabetically and prints
the sorted sentence.
Experiment No. 5
Write a program to implement Hangman game using python.
Objective:
To guess a hidden word by entering letters until the player wins or loses.
Sample Run:
Hidden Word: apple
User guesses letters until they complete the word.

Sample Input:

Word = python

Sample Output:

______

You win! / You lose!

Algorithm:

1. Hide word with _.


2. Ask for letter input.
3. Reveal letters if guessed correctly.
4. Reduce lives on wrong guesses.
5. Stop when word is guessed or lives end.

Python Code:
word = "python"
g = ["_"] * len(word)
life = 6

while life > 0 and "_" in g:


print("Word:", " ".join(g))
ch = input("Enter a letter: ")

if ch in word:
for i in range(len(word)):
if word[i] == ch:
g[i] = ch
else:
life -= 1
print("Wrong! Lives left:", life)
if "_" not in g:
print("You won!")
else:
print("You lost. Word was:", word)

Output:

Output Analysis:
Player uncovers letters step-by-step until full word is revealed.

Correct letters are revealed steadily until the whole word is known.
Experiment No. 6
Write a program to implement Tic-Tac-Toe game using python.

Objective:
To create a simple two-player (X and O) game on a 3×3 grid.
Players take turns to mark positions and win by forming 3 in a row.

Sample Input:

User enters cell positions 0–8.

Sample Output:

Winner or draw message.

Algorithm:

1. Show board each turn.


2. Player enters position.
3. Insert symbol (X or O).
4. Check winning combinations.
5. Continue until win or draw.

Python Code:
board = [" "] * 9

def show():
print(board[0],"|",board[1],"|",board[2])
print("---------")
print(board[3],"|",board[4],"|",board[5])
print("---------")
print(board[6],"|",board[7],"|",board[8])

def win(s):
ways = [(0,1,2),(3,4,5),(6,7,8),(0,3,6),
(1,4,7),(2,5,8),(0,4,8),(2,4,6)]
for a,b,c in ways:
if board[a] == board[b] == board[c] == s:
return True
return False

turn = "X"
for _ in range(9):
show()
pos = int(input("Enter 0-8: "))
if board[pos] == " ":
board[pos] = turn
if win(turn):
show()
print(turn, "wins!")
break
turn = "O" if turn == "X" else "X"
else:
show()
print("Draw!")

Output:

Output Analysis:
Players take turns until someone wins or the game draws.

Whenever 3 same symbols align, that symbol wins


Experiment No. 7
Write a python program to remove stop words for a given passage from a
text file using NLTK.

Objective:
To clean text by removing common English words like the, is, an which don’t add meaning.
Stop words are common words like the, is, in, a, which usually add no meaning in NLP.
This program reads a file, removes these stop words, and prints clean text.

Sample Input:

“Python is a very good programming language.”

Sample Output:

“Python good programming language .”

Algorithm:

1. Import NLTK and download data.


2. Read text from file.
3. Tokenize words.
4. Load stop words list.
5. Remove them from text.
6. Print cleaned text.

Python Code:

import nltk

from [Link] import stopwords

from [Link] import word_tokenize

from [Link] import files

uploaded = [Link]()

# Get the filename (first uploaded file)

filename = list([Link]())[0]
[Link]('punkt')

[Link]('punkt_tab')

[Link]('stopwords')

# Read the uploaded file

with open(filename, "r") as f:

text = [Link]()

words = word_tokenize(text)

# Get English stopwords

stop_words = set([Link]("english"))

# Remove stopwords

cleaned_text = [word for word in words if [Link]() not in stop_words]

print("Original Text:\n", text)

print("\nAfter Removing Stop Words:\n", " ".join(cleaned_text))

Output:

Output Analysis:

Words like is, a, very are removed because they don't add meaning. sample sentence
showing removal stop words
Experiment No. 8
Write a python program to implement stemming for a given sentence
using NLTK.

Objective:
To reduce words to their root form. Stemming converts words to their root form (play,
played, playing → play).
Useful to reduce word variations in NLP tasks.

Sample Input :

“Players are playing in the field”

Sample Output:

“player are play in the field”

Algorithm:

1. Load PorterStemmer.
2. Tokenize sentence.
3. Apply stemmer to each word.

Python Code:
import nltk
from [Link] import PorterStemmer
from [Link] import word_tokenize

[Link]('punkt')

text = "Players are playing in the field"


ps = PorterStemmer()

w = word_tokenize(text)
st = [[Link](i) for i in w]

print("Original:", text)
print("Stemmed:", " ".join(st))
Output:

Output Analysis:

playing -> play


played -> play
player -> player
happily -> happily

Each word becomes short and root-like form.


Experiment No. 9
Write a python program to POS (Parts of Speech) tagging for the give
sentence using NLTK.

Objective:
POS tagging identifies parts of speech like noun, verb, adjective, etc., for each word in a
sentence.

Sample Input:

“Python makes coding easy”

Sample Output:

List of (word, POS-tag) pairs.

Algorithm:

1. Tokenize words.
2. Use pos_tag() to assign grammar labels.

Python Code:
import nltk

from [Link] import word_tokenize

# Download everything POS tagger needs

[Link]('punkt')

[Link]('wordnet')

[Link]('averaged_perceptron_tagger')

[Link]('averaged_perceptron_tagger_eng')

[Link]('maxent_ne_chunker')

[Link]('words')

# Extra: download all taggers (fixes most lookup errors)


[Link]('taggers')

text = "Python makes coding easy"

w = word_tokenize(text)

tags = nltk.pos_tag(w)

print("POS Tags:")

print(tags)

Output:

Output Analysis:

1. Each word is tagged with its part of speech: noun, verb, adjective, etc.
2. Example:
3. Python → NNP (proper noun)
4. makes → VBZ (verb, 3rd person singular)
5. good → JJ (adjective)
6. Helps in understanding grammar structure, parsing sentences, and NLP tasks
like information extraction.
Experiment No. 10
Write a python program to implement Lemmatization using NLTK.

Objective:
Lemmatization converts words to dictionary form based on meaning
(boys → boy, better → good).
More accurate than stemming.
Sample Input:

“The boys are playing in the gardens”

Expected Output:

”The boy are playing in the garden”

Algorithm:

1. Load WordNetLemmatizer.
2. Tokenize words.
3. Apply .lemmatize() on each word.

Python Code:
import nltk
from [Link] import WordNetLemmatizer
from [Link] import word_tokenize

[Link]('punkt')
[Link]('wordnet')

text = "The boys are playing in the gardens"


lm = WordNetLemmatizer()

w = word_tokenize(text)
lem = [[Link](i) for i in w]

print("Original:", text)
print("Lemmatized:", " ".join(lem))
Output:

Output Analysis:

1. Words are converted to dictionary/base form: plural → singular, better → good.


2. Example:
3. "boys" → "boy"
4. "gardens" → "garden"
5. Unlike stemming, lemmatization considers actual meaning.
6. Useful for text normalization in NLP.
Experiment No. 11
Write a python program to for Text Classification for the give sentence
using NLTK.

Objective:
To classify a given sentence into predefined categories like positive/negative, spam/ham, or
sports/politics using NLTK.
We will create a small training dataset, extract features (like word presence), train a Naive
Bayes classifier, and then predict the category of a new sentence.
This teaches basic NLP classification and machine learning concepts.

Sample Input:

[("I love this movie", "positive"),


("This is a great book", "positive"),
("I hate this weather", "negative"),
("This movie is terrible", "negative")]

Test sentence:

"I love this book"

Expected Output:

The sentence is classified as: positive

Algorithm:

1. Import NLTK and prepare a small labeled dataset.


2. Define a feature extraction function (like which words are present).
3. Train a Naive Bayes classifier using the training dataset.
4. Take the new sentence, extract features, and classify it.
5. Print the predicted label

Python Code:
import nltk

from [Link] import WordNetLemmatizer


from [Link] import word_tokenize

[Link]('punkt')
[Link]('wordnet')
text = "The boys are playing in the gardens"
lm = WordNetLemmatizer()

w = word_tokenize(text)
lem = [[Link](i) for i in w]

print("Original:", text)
print("Lemmatized:", " ".join(lem))

Output:

Output Analysis:

The classifier checks which words in the test sentence match words in the training set.
Since "love" and "book" are mostly seen in positive sentences in the training data, the
classifier predicts positive.

You might also like