Python Programs( Water jug Problem)
Python Programs( Water jug Problem)
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)
Output
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),
(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
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 = '''!()-[]{};:'"\,<>./?@#$%^&*_~'''
# 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
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()
return sorted_sentence
# Example usage
Output
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}")
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)
Output
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]
# 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
print_board(board)
Output
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
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')
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()
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)
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
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()
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
Practical No. – 9
Write a python program to implement stemming for a given sentence using NLTK.
Solution :
import nltk
def pos_tag_sentence(sentence):
# Tokenize the sentence into words
words = nltk.word_tokenize(sentence)
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)
Output
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
def lemmatize_sentence(sentence):
# Initialize the WordNet Lemmatizer
lemmatizer = WordNetLemmatizer()
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)
Output
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
# 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"),
]
processed_data.append((words, label))
return 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
# 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}")
Output
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))
while queue:
current_state = queue.popleft()
if current_state.is_goal():
return current_state
return None
def print_solution(solution):
path = []
while solution:
path.append(solution.board)
solution = solution.previous
for step in reversed(path):
print(step)
solution = bfs(initial_state)
if solution:
print("Solution found in", solution.moves, "moves:")
print_solution(solution)
else:
print("No solution exists.")
Output