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

Python Programs( Water jug Problem)

The document contains several Python programming practicals, including implementations for Breadth First Search and Depth First Search traversals, a Water Jug problem, punctuation removal, sentence sorting, a Hangman game, a Tic-Tac-Toe game, and a stop word removal program using NLTK. Each practical includes code solutions and example usage. The content is approved by AICTE and affiliated with Dr. APJ Abdul Kalam Technical University.
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)
19 views26 pages

Python Programs( Water jug Problem)

The document contains several Python programming practicals, including implementations for Breadth First Search and Depth First Search traversals, a Water Jug problem, punctuation removal, sentence sorting, a Hangman game, a Tic-Tac-Toe game, and a stop word removal program using NLTK. Each practical includes code solutions and example usage. The content is approved by AICTE and affiliated with Dr. APJ Abdul Kalam Technical University.
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

[Approved by AICTE,Govt. of India & Affiliated to Dr.

APJ Abdul Kalam


Technical University ,Lucknow ,U.P. India]
Department of Computer Science and Engineering (AI)

Practical No. – 1
Write a python program to implement Breadth First Search Traversal and Depth First Search
Traversal.
Solution :
from collections import deque
class Graph:
def __init__(self):
self.adj_list = {}
def add_vertex(self, vertex):
if vertex not in self.adj_list:
self.adj_list[vertex] = []
def add_edge(self, vertex1, vertex2):
if vertex1 in self.adj_list and vertex2 in self.adj_list:
self.adj_list[vertex1].append(vertex2)
self.adj_list[vertex2].append(vertex1)
def bfs_traversal(self, start_vertex):
visited = set()
traversal_order = []
queue = deque([start_vertex])
while queue:
vertex = queue.popleft()
if vertex not in visited:
visited.add(vertex)
traversal_order.append(vertex)
for neighbor in self.adj_list[vertex]:
if neighbor not in visited:
queue.append(neighbor)
return traversal_order
def dfs_traversal(self, start_vertex):
visited = set()
traversal_order = []
def dfs_helper(vertex):
visited.add(vertex)
traversal_order.append(vertex)

Tanish Chauhan 2201921520215 1


[Approved by AICTE,Govt. of India & Affiliated to Dr. APJ Abdul Kalam
Technical University ,Lucknow ,U.P. India]
Department of Computer Science and Engineering (AI)

for neighbor in self.adj_list[vertex]:


if neighbor not in visited:
dfs_helper(neighbor)
dfs_helper(start_vertex)
return traversal_order
# Create a graph
g = Graph()
g.add_vertex('A')
g.add_vertex('B')
g.add_vertex('C')
g.add_vertex('D')
g.add_vertex('E')
g.add_edge('A', 'B')
g.add_edge('A', 'C')
g.add_edge('B', 'D')
g.add_edge('C', 'E')
g.add_edge('D', 'E')
# Perform BFS traversal
print("BFS Traversal:")
print(g.bfs_traversal('A')) # Output: ['A', 'B', 'C', 'D', 'E']
# Perform DFS traversal
print("DFS Traversal:")
print(g.dfs_traversal('A')) # Output: ['A', 'B', 'D', 'E', 'C']

Output

Tanish Chauhan 2201921520215 2


[Approved by AICTE,Govt. of India & Affiliated to Dr. APJ Abdul Kalam
Technical University ,Lucknow ,U.P. India]
Department of Computer Science and Engineering (AI)

Practical No. – 2
Write a python program to implement Water Jug Problem.
Solution :
from collections import deque

class WaterJugProblem:
def __init__(self, jug1_capacity, jug2_capacity, target):
self.jug1_capacity = jug1_capacity
self.jug2_capacity = jug2_capacity
self.target = target
def bfs(self):
# Queue for BFS
queue = deque()
# Set to keep track of visited states
visited = set()
# Initial state (0, 0) - both jugs are empty
initial_state = (0, 0)
queue.append(initial_state)
visited.add(initial_state)
while queue:
jug1, jug2 = queue.popleft()
print(f"Current state: Jug1 = {jug1}, Jug2 = {jug2}")
# Check if we have reached the target
if jug1 == self.target or jug2 == self.target:
print("Target reached!")
return True
# Possible next states
next_states = [
(self.jug1_capacity, jug2),
(jug1, self.jug2_capacity),
(0, jug2),
(jug1, 0),
(min(jug1 + jug2, self.jug1_capacity), jug2 - (self.jug1_capacity - jug1) if jug1 + jug2 >
self.jug1_capacity else 0),

Tanish Chauhan 2201921520215 3


[Approved by AICTE,Govt. of India & Affiliated to Dr. APJ Abdul Kalam
Technical University ,Lucknow ,U.P. India]
Department of Computer Science and Engineering (AI)

(jug1 - (self.jug2_capacity - jug2) if jug1 + jug2 > self.jug2_capacity else 0, min(jug1 + jug2,
self.jug2_capacity))
]
for state in next_states:
if state not in visited:
visited.add(state)
queue.append(state)
print("Target not reachable.")
return False
# Example usage
if __name__ == "__main__":
jug1_capacity = 4
jug2_capacity = 3
target = 2
problem = WaterJugProblem(jug1_capacity, jug2_capacity, target)
problem.bfs()

Output

Tanish Chauhan 2201921520215 4


[Approved by AICTE,Govt. of India & Affiliated to Dr. APJ Abdul Kalam
Technical University ,Lucknow ,U.P. India]
Department of Computer Science and Engineering (AI)

Practical No. – 3
Write a python program to remove punctuations from the given string.
Solution :
def remove_punctuation(input_string):
# Define the punctuation characters to remove
punctuation = '''!()-[]{};:'"\,<>./?@#$%^&*_~'''

# Create a translation table that maps each punctuation to None


translator = str.maketrans('', '', punctuation)

# Use the translate method to remove punctuation


return input_string.translate(translator)

# Example usage
input_string = "Hello, Everyone! I am Utkarsh Pandey: does it work?"
result = remove_punctuation(input_string)
print("Original String:", input_string)
print("String without Punctuation:", result)

Output

Tanish Chauhan 2201921520215 5


[Approved by AICTE,Govt. of India & Affiliated to Dr. APJ Abdul Kalam
Technical University ,Lucknow ,U.P. India]
Department of Computer Science and Engineering (AI)

Practical No. – 4
Write a python program to sort the sentence in alphabetical order.
Solution :
def sort_sentence(sentence):
# Split the sentence into words
words = sentence.split()

# Sort the words alphabetically


sorted_words = sorted(words, key=str.lower)

# Join the sorted words back into a sentence


sorted_sentence = ' '.join(sorted_words)

return sorted_sentence

# Example usage

input_sentence = "Hello Everyone I am Utkarsh Pandey"


sorted_sentence = sort_sentence(input_sentence)
print("Original Sentence:", input_sentence)
print("Sorted Sentence:", sorted_sentence)

Output

Tanish Chauhan 2201921520215 6


[Approved by AICTE,Govt. of India & Affiliated to Dr. APJ Abdul Kalam
Technical University ,Lucknow ,U.P. India]
Department of Computer Science and Engineering (AI)

Practical No. – 5
Write a program to implement Hangman game using python.
Solution :
import random
def hangman():
# List of possible words
words = ["hello", "everyone", "i", "am", "Utkarsh ", "Pandey"]
word = random.choice(words).lower() # Randomly select a word
word_letters = set(word) # Set of letters in the word
guessed_letters = set() # Set to keep track of guessed letters
attempts = 6 # Number of attempts

print("Welcome to Hangman!")
print(f"The word has {len(word)} letters. You have {attempts} attempts to guess it.")

# Game loop
while attempts > 0 and word_letters:
# Display current guessed word
current_word = [letter if letter in guessed_letters else "_" for letter in word]
print("Current word:", " ".join(current_word))
print(f"Guessed letters: {', '.join(sorted(guessed_letters)) if guessed_letters else 'None'}")
print(f"Remaining attempts: {attempts}")

# Ask user for a guess


guess = input("Enter a letter: ").lower()

if len(guess) != 1 or not guess.isalpha():


print("Invalid input. Please enter a single letter.")
continue

Tanish Chauhan 2201921520215 7


[Approved by AICTE,Govt. of India & Affiliated to Dr. APJ Abdul Kalam
Technical University ,Lucknow ,U.P. India]
Department of Computer Science and Engineering (AI)

if guess in guessed_letters:
print("You already guessed that letter. Try a different one.")
continue

guessed_letters.add(guess)
if guess in word_letters:
word_letters.remove(guess)
print("Good guess!")
else:
attempts -= 1
print("Wrong guess! You lost an attempt.")

print("-" * 30)

# End of the game


if not word_letters:
print(f"Congratulations! You guessed the word: {word}")
else:
print(f"Out of attempts! The word was: {word}")
print("Thanks for playing Hangman!")

# Run the Hangman game


hangman()

Output

Tanish Chauhan 2201921520215 8


[Approved by AICTE,Govt. of India & Affiliated to Dr. APJ Abdul Kalam
Technical University ,Lucknow ,U.P. India]
Department of Computer Science and Engineering (AI)

Practical No. – 6
Write a program to implement Tic-Tac-Toe game using python.
Solution :
def print_board(board):
"""Print the current state of the board."""
print("\n")
for row in board:
print(" | ".join(row))
print("-" * 5)
print("\n")

def check_winner(board):
"""Check if there's a winner."""
# Check rows and columns
for i in range(3):
if board[i][0] == board[i][1] == board[i][2] != " ":
return board[i][0]
if board[0][i] == board[1][i] == board[2][i] != " ":
return board[0][i]

Tanish Chauhan 2201921520215 9


[Approved by AICTE,Govt. of India & Affiliated to Dr. APJ Abdul Kalam
Technical University ,Lucknow ,U.P. India]
Department of Computer Science and Engineering (AI)

# Check diagonals
if board[0][0] == board[1][1] == board[2][2] != " ":
return board[0][0]
if board[0][2] == board[1][1] == board[2][0] != " ":
return board[0][2]
return None

def is_draw(board):
"""Check if the game is a draw."""
return all(cell != " " for row in board for cell in row)

def play_tic_tac_toe():
"""Main function to play the Tic-Tac-Toe game."""
# Initialize the board
board = [[" " for _ in range(3)] for _ in range(3)]
current_player = "X"

print("Welcome to Tic-Tac-Toe!")
print_board(board)
# Main game loop
while True:
try:
# Get player's move
print(f"Player {current_player}, it's your turn!")
row = int(input("Enter the row (1-3): ")) - 1
col = int(input("Enter the column (1-3): ")) - 1

# Check if the move is valid


if row not in range(3) or col not in range(3) or board[row][col] != " ":
print("Invalid move. Try again.")
continue

# Make the move


board[row][col] = current_player

Tanish Chauhan 2201921520215 10


[Approved by AICTE,Govt. of India & Affiliated to Dr. APJ Abdul Kalam
Technical University ,Lucknow ,U.P. India]
Department of Computer Science and Engineering (AI)

print_board(board)

# Check for a winner


winner = check_winner(board)
if winner:
print(f"Player {winner} wins! Congratulations!")
break
# Check for a draw
if is_draw(board):
print("It's a draw!")
break
current_player = "O" if current_player == "X" else "X"
except ValueError:
print("Invalid input. Please enter a number between 1 and 3.")
if __name__ == "__main__":
play_tic_tac_toe()

Tanish Chauhan 2201921520215 11


[Approved by AICTE,Govt. of India & Affiliated to Dr. APJ Abdul Kalam
Technical University ,Lucknow ,U.P. India]
Department of Computer Science and Engineering (AI)

Output

Tanish Chauhan 2201921520215 12


[Approved by AICTE,Govt. of India & Affiliated to Dr. APJ Abdul Kalam
Technical University ,Lucknow ,U.P. India]
Department of Computer Science and Engineering (AI)

Tanish Chauhan 2201921520215 13


[Approved by AICTE,Govt. of India & Affiliated to Dr. APJ Abdul Kalam
Technical University ,Lucknow ,U.P. India]
Department of Computer Science and Engineering (AI)

Practical No. – 7
Write a python program to remove stop words for a given passage from a text file using NLTK.
Solution :
import nltk
import string
import sys

from nltk.corpus import stopwords


from nltk.tokenize import word_tokenize

def download_stopwords():
"""
Downloads the NLTK stopwords corpus if not already downloaded.
"""
try:
stopwords.words('english')
except LookupError:
print("Downloading NLTK stopwords corpus...")
nltk.download('stopwords')
try:
nltk.data.find('tokenizers/punkt')
except LookupError:
print("Downloading NLTK punkt tokenizer...")
nltk.download('punkt')

def remove_stop_words(input_file, output_file):


"""
Removes stop words from the text in the input file and writes the result to the output file.

Parameters:
- input_file: Path to the input text file.
- output_file: Path to the output text file where cleaned text will be saved.
"""
# Ensure necessary NLTK data is downloaded
Tanish Chauhan 2201921520215 14
[Approved by AICTE,Govt. of India & Affiliated to Dr. APJ Abdul Kalam
Technical University ,Lucknow ,U.P. India]
Department of Computer Science and Engineering (AI)

download_stopwords()

# Define English stop words


stop_words = set(stopwords.words('english'))

# Define punctuation to remove


punctuation = set(string.punctuation)

try:
# Read the input file
with open(input_file, 'r', encoding='utf-8') as file:
text = file.read()
except FileNotFoundError:
print(f"Error: The file '{input_file}' does not exist.")
sys.exit(1)

# Tokenize the text into words


words = word_tokenize(text)

# Remove stop words and punctuation, and convert to lower case


filtered_words = [
word for word in words
if word.lower() not in stop_words and word not in punctuation
]

# Reconstruct the text from filtered words


cleaned_text = ' '.join(filtered_words)

# Write the cleaned text to the output file


with open(output_file, 'w', encoding='utf-8') as file:
file.write(cleaned_text)

print(f"Stop words removed. Cleaned text saved to '{output_file}'.")

Tanish Chauhan 2201921520215 15


[Approved by AICTE,Govt. of India & Affiliated to Dr. APJ Abdul Kalam
Technical University ,Lucknow ,U.P. India]
Department of Computer Science and Engineering (AI)

def main():
"""
Main function to execute the stop word removal process.
"""
if len(sys.argv) != 3:
print("Usage: python remove_stopwords.py <input_file> <output_file>")
sys.exit(1)

input_file = sys.argv[1]
output_file = sys.argv[2]

remove_stop_words(input_file, output_file)

if __name__ == "__main__":
main()

Output

Tanish Chauhan 2201921520215 16


[Approved by AICTE,Govt. of India & Affiliated to Dr. APJ Abdul Kalam
Technical University ,Lucknow ,U.P. India]
Department of Computer Science and Engineering (AI)

Practical No. – 8
Write a python program to implement stemming for a given sentence using NLTK.

Solution :
import nltk
from nltk.stem import PorterStemmer
from nltk.tokenize import word_tokenize
# Ensure you have the necessary NLTK resources
nltk.download('punkt')
def stem_sentence(sentence):
# Initialize the Porter Stemmer
stemmer = PorterStemmer()

# Tokenize the sentence into words


words = word_tokenize(sentence)

# Stem each word in the list of words


stemmed_words = [stemmer.stem(word) for word in words]

# Join the stemmed words back into a sentence


stemmed_sentence = ' '.join(stemmed_words)

return stemmed_sentence
# Example usage

input_sentence = "The children are playing in the playground and enjoying their games."
stemmed_sentence = stem_sentence(input_sentence)
print("Original Sentence:", input_sentence)
print("Stemmed Sentence:", stemmed_sentence)

Output

Tanish Chauhan 2201921520215 17


[Approved by AICTE,Govt. of India & Affiliated to Dr. APJ Abdul Kalam
Technical University ,Lucknow ,U.P. India]
Department of Computer Science and Engineering (AI)

Practical No. – 9
Write a python program to implement stemming for a given sentence using NLTK.

Solution :
import nltk

# Ensure you have the necessary NLTK resources


nltk.download('punkt')
nltk.download('averaged_perceptron_tagger')

def pos_tag_sentence(sentence):
# Tokenize the sentence into words
words = nltk.word_tokenize(sentence)

# Perform POS tagging


pos_tags = nltk.pos_tag(words)

return pos_tags

# Example usage
if __name__ == "__main__":
input_sentence = "The quick brown fox jumps over the lazy dog."
pos_tags = pos_tag_sentence(input_sentence)

print("Original Sentence:", input_sentence)


print("POS Tags:", pos_tags)

Output

Tanish Chauhan 2201921520215 18


[Approved by AICTE,Govt. of India & Affiliated to Dr. APJ Abdul Kalam
Technical University ,Lucknow ,U.P. India]
Department of Computer Science and Engineering (AI)

Practical No. – 10
Write a python program to implement stemming for a given sentence using NLTK.

Solution :
import nltk
from nltk.stem import WordNetLemmatizer
from nltk.tokenize import word_tokenize

# Ensure you have the necessary NLTK resources


nltk.download('punkt')
nltk.download('wordnet')

def lemmatize_sentence(sentence):
# Initialize the WordNet Lemmatizer
lemmatizer = WordNetLemmatizer()

# Tokenize the sentence into words


words = word_tokenize(sentence)

# Lemmatize each word in the list of words


lemmatized_words = [lemmatizer.lemmatize(word) for word in words]

# Join the lemmatized words back into a sentence


lemmatized_sentence = ' '.join(lemmatized_words)

return lemmatized_sentence

# Example usage
if __name__ == "__main__":
input_sentence = "The children are playing in the playground and enjoying their games."
lemmatized_sentence = lemmatize_sentence(input_sentence)
print("Original Sentence:", input_sentence)
print("Lemmatized Sentence:", lemmatized_sentence)

Tanish Chauhan 2201921520215 19


[Approved by AICTE,Govt. of India & Affiliated to Dr. APJ Abdul Kalam
Technical University ,Lucknow ,U.P. India]
Department of Computer Science and Engineering (AI)

Output

Tanish Chauhan 2201921520215 20


[Approved by AICTE,Govt. of India & Affiliated to Dr. APJ Abdul Kalam
Technical University ,Lucknow ,U.P. India]
Department of Computer Science and Engineering (AI)

Practical No. – 11
Write a python program to for Text Classification for the give sentence using NLTK.

Solution :
import nltk
import random
from nltk.classify import NaiveBayesClassifier
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords

# Ensure you have the necessary NLTK resources


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

# Sample dataset
data = [
("I love programming in Python", "positive"),
("Python is a great language", "positive"),
("I hate bugs in my code", "negative"),
("Debugging is so frustrating", "negative"),
("I enjoy solving problems", "positive"),
("This code is terrible", "negative"),
("I am learning new things", "positive"),
("This is a bad experience", "negative"),
]

# Preprocess the data


def preprocess_data(data):
stop_words = set(stopwords.words('english'))
processed_data = []

for sentence, label in data:


words = word_tokenize(sentence.lower())
words = [word for word in words if word.isalnum() and word not in stop_words]

Tanish Chauhan 2201921520215 21


[Approved by AICTE,Govt. of India & Affiliated to Dr. APJ Abdul Kalam
Technical University ,Lucknow ,U.P. India]
Department of Computer Science and Engineering (AI)

processed_data.append((words, label))

return processed_data

# Extract features from the data


def extract_features(words):
return {word: True for word in words}

# Prepare the training data


processed_data = preprocess_data(data)
featuresets = [(extract_features(words), label) for (words, label) in processed_data]

# Shuffle the dataset and split into training and testing sets
random.shuffle(featuresets)
train_set = featuresets[:6] # 75% for training
test_set = featuresets[6:] # 25% for testing

# Train the Naive Bayes classifier


classifier = NaiveBayesClassifier.train(train_set)

# Function to classify a new sentence


def classify_sentence(sentence):
words = word_tokenize(sentence.lower())
words = [word for word in words if word.isalnum() and word not in stopwords.words('english')]
features = extract_features(words)
return classifier.classify(features)

# Example usage
if __name__ == "__main__":
test_sentence = "I am excited about coding!"
classification = classify_sentence(test_sentence)
print(f"Sentence: '{test_sentence}' is classified as: {classification}")

# Test the classifier on the test set

Tanish Chauhan 2201921520215 22


[Approved by AICTE,Govt. of India & Affiliated to Dr. APJ Abdul Kalam
Technical University ,Lucknow ,U.P. India]
Department of Computer Science and Engineering (AI)

accuracy = nltk.classify.util.accuracy(classifier, test_set)


print(f"Classifier accuracy: {accuracy:.2f}")

Output

Tanish Chauhan 2201921520215 23


[Approved by AICTE,Govt. of India & Affiliated to Dr. APJ Abdul Kalam
Technical University ,Lucknow ,U.P. India]
Department of Computer Science and Engineering (AI)

Practical No. – 12
Write a python program to implement 8 puzzle problem using BFS.
Solution :
from collections import deque

class PuzzleState:
def __init__(self, board, empty_tile_pos, moves=0, previous=None):
self.board = board
self.empty_tile_pos = empty_tile_pos
self.moves = moves
self.previous = previous

def is_goal(self):
return self.board == [1, 2, 3, 4, 5, 6, 7, 8, 0]

def get_neighbors(self):
neighbors = []
x, y = self.empty_tile_pos
directions = [(1, 0), (-1, 0), (0, 1), (0, -1)] # Down, Up, Right, Left
for dx, dy in directions:
new_x, new_y = x + dx, y + dy
if 0 <= new_x < 3 and 0 <= new_y < 3:
new_board = self.board[:]
# Swap the empty tile with the adjacent tile
new_board[x * 3 + y], new_board[new_x * 3 + new_y] = new_board[new_x * 3 + new_y],
new_board[x * 3 + y]
neighbors.append(PuzzleState(new_board, (new_x, new_y), self.moves + 1, self))
return neighbors

def bfs(initial_state):
queue = deque([initial_state])
visited = set()
visited.add(tuple(initial_state.board))

Tanish Chauhan 2201921520215 24


[Approved by AICTE,Govt. of India & Affiliated to Dr. APJ Abdul Kalam
Technical University ,Lucknow ,U.P. India]
Department of Computer Science and Engineering (AI)

while queue:
current_state = queue.popleft()

if current_state.is_goal():
return current_state

for neighbor in current_state.get_neighbors():


if tuple(neighbor.board) not in visited:
visited.add(tuple(neighbor.board))
queue.append(neighbor)

return None

def print_solution(solution):
path = []
while solution:
path.append(solution.board)
solution = solution.previous
for step in reversed(path):
print(step)

# Initial configuration of the puzzle


initial_board = [1, 2, 3, 4, 5, 6, 0, 7, 8] # 0 represents the empty tile
empty_tile_pos = (2, 0) # Row, Column position of the empty tile

initial_state = PuzzleState(initial_board, empty_tile_pos)

solution = bfs(initial_state)

if solution:
print("Solution found in", solution.moves, "moves:")
print_solution(solution)
else:
print("No solution exists.")

Tanish Chauhan 2201921520215 25


[Approved by AICTE,Govt. of India & Affiliated to Dr. APJ Abdul Kalam
Technical University ,Lucknow ,U.P. India]
Department of Computer Science and Engineering (AI)

Output

Tanish Chauhan 2201921520215 26

You might also like