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

AI LAB file

The document contains ten Python programming labs covering various algorithms and tasks, including Breadth First Search, the Water Jug Problem, string manipulation, sorting, and games like Hangman and Tic-Tac-Toe. It also includes natural language processing tasks such as removing stop words, stemming, POS tagging, and lemmatization using NLTK. Each lab provides code examples, expected outputs, and explanations of the implemented concepts.

Uploaded by

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

AI LAB file

The document contains ten Python programming labs covering various algorithms and tasks, including Breadth First Search, the Water Jug Problem, string manipulation, sorting, and games like Hangman and Tic-Tac-Toe. It also includes natural language processing tasks such as removing stop words, stemming, POS tagging, and lemmatization using NLTK. Each lab provides code examples, expected outputs, and explanations of the implemented concepts.

Uploaded by

Ritiz Shukla
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

LAB – 1

Program : Write a python program to implement Breadth First Search Traversal?


Code:
from collections import deque
class Graph:
def __init__(self):
self.graph = {}

def add_edge(self, u, v):


if u not in self.graph:
self.graph[u] = []
if v not in self.graph:
self.graph[v] = []
self.graph[u].append(v)
self.graph[v].append(u)

def bfs(self, start):


visited = set()
queue = deque([start])
visited.add(start)

while queue:
vertex = queue.popleft()
print(vertex, end=' ')

for neighbor in self.graph.get(vertex, []):


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

if __name__ == "__main__":

pg. 1
g = Graph()
g.add_edge(0, 1)
g.add_edge(0, 2)
g.add_edge(1, 3)
g.add_edge(1, 4)
g.add_edge(2, 5)
g.add_edge(2, 6)

print("Breadth First Search starting from vertex 0:")


g.bfs(0)

Output :
Breadth First Search starting from vertex 0:
0123456

pg. 2
LAB – 2

Program : Write a python program to implement Water Jug Problem?


Code:
from collections import deque

def water_jug_problem(capacity_a, capacity_b, target):


queue = deque()
visited = set()
initial_state = (0, 0)
queue.append(initial_state)
visited.add(initial_state)

while queue:
current_a, current_b = queue.popleft()

if current_a == target or current_b == target:


return True

possible_states = [
(capacity_a, current_b),
(current_a, capacity_b),
(0, current_b),
(current_a, 0),
(max(0, current_a - (capacity_b - current_b)), current_b + min(current_a, capacity_b -
current_b)),
(current_a + min(current_b, capacity_a - current_a), max(0, current_b - (capacity_a -
current_a)))
]

for state in possible_states:


if state not in visited:
visited.add(state)

pg. 3
queue.append(state)

return False

if __name__ == "__main__":
capacity_a = 4
capacity_b = 3
target = 2

if water_jug_problem(capacity_a, capacity_b, target):


print(f"It is possible to measure {target} liters of water.")
else:
print(f"It is not possible to measure {target} liters of water.")

OUTPUT:
It is possible to measure 2 liters of water.

pg. 4
LAB – 3

PROGRAM : Write a python program to remove punctuations from the given string?
CODE :
import string
def remove_punctuation(input_string):
# Create a translation table that maps punctuation to None
translator = str.maketrans('', '', string.punctuation)
# Translate the input string using the translation table
return input_string.translate(translator)

if __name__ == "__main__":
input_string = "Hello, World! This is a test string with punctuation: @#%&*()!"
result = remove_punctuation(input_string)
print("Original String:", input_string)
print("String without Punctuation:", result)

OUTPUT :
Original String: Hello, World! This is a test string with punctuation: @#%&*()!
String without Punctuation: Hello World This is a test string with punctuation

pg. 5
LAB – 4

PROGRAM : Write a python program to sort the sentence in alphabetical order?


CODE :
def sort_sentence_alphabetically(sentence):
# Split the sentence into words
words = sentence.split()
# Sort the list of words
sorted_words = sorted(words)
# Join the sorted words back into a sentence
sorted_sentence = ' '.join(sorted_words)
return sorted_sentence

if __name__ == "__main__":
input_sentence = "the quick brown fox jumps over the lazy dog"
result = sort_sentence_alphabetically(input_sentence)
print("Original Sentence:", input_sentence)
print("Sorted Sentence:", result)

OUTPUT :
Original Sentence: the quick brown fox jumps over the lazy dog
Sorted Sentence: brown dog fox jumps lazy over quick the the

pg. 6
LAB – 5

PROGRAM : Write a program to implement Hangman game using python


CODE :
import random

def hangman():
word_list = ["python", "java", "javascript", "c++", "c#"]
chosen_word = random.choice(word_list)

guesses = []
max_guesses = 6

while max_guesses > 0:


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

if guess in guesses:
print("You already guessed that letter.")
continue

guesses.append(guess)

if guess not in chosen_word:


max_guesses -= 1
print(f"Incorrect guess. {max_guesses} guesses remaining.")

word_display = ""
for letter in chosen_word:
if letter in guesses:
word_display += letter
else:
word_display += "_"

pg. 7
print(word_display)

if "_" not in word_display:


print("Congratulations! You win!")
break

if "_" in word_display:
print(f"You lose. The word was {chosen_word}")

hangman()

OUTPUT :
Guess a letter: c
c_
Guess a letter: #
c#
Congratulations! You win!

pg. 8
LAB – 6

PROGRAM : Write a program to implement Tic-Tac-Toe game using python.


CODE :
def draw_board(board):
print('-------------')
for row in range(3):
print('|', end='')
for col in range(3):
print(f' {board[row][col]} |', end='')
print('\n-------------')

def check_win(board, player):


for row in range(3):
if board[row][0] == board[row][1] == board[row][2] == player:
return True
for col in range(3):
if board[0][col] == board[1][col] == board[2][col] == player:
return True

if board[0][0] == board[1][1] == board[2][2] == player:


return True
if board[0][2] == board[1][1] == board[2][0] == player:
return True
return False

def check_draw(board):
for row in range(3):
for col in range(3):
if board[row][col] == ' ':
return False
return True

pg. 9
def tic_tac_toe():
board = [[' ' for _ in range(3)] for _ in range(3)]
current_player = 'X'

while True:
draw_board(board)

row = int(input(f"Player {current_player}, enter row (0, 1, 2): "))


col = int(input(f"Player {current_player}, enter column (0, 1, 2): "))

if row < 0 or row > 2 or col < 0 or col > 2 or board[row][col] != ' ':
print("Invalid move. Try again.")
continue

board[row][col] = current_player

if check_win(board, current_player):
draw_board(board)
print(f"Player {current_player} wins!")
break

if check_draw(board):
draw_board(board)
print("It's a draw!")
break

current_player = 'O' if current_player == 'X' else 'X'

tic_tac_toe()

pg. 10
OUTPUT :
-------------
| | | |
-------------
| | | |
-------------
| | | |
-------------
Player X, enter row (0, 1, 2): 0
Player X, enter column (0, 1, 2): 0
-------------
|X| | |
-------------
| | | |
-------------
| | | |
-------------
Player O, enter row (0, 1, 2): 1
Player O, enter column (0, 1, 2): 2
-------------
|X| | |
-------------
| | |O|
-------------
| | | |
-------------
Player X, enter row (0, 1, 2): 1
Player X, enter column (0, 1, 2): 1
-------------
|X| | |
-------------
| |X|O|

pg. 11
-------------
| | | |
-------------
Player O, enter row (0, 1, 2): 2
Player O, enter column (0, 1, 2): 1
-------------
|X| | |
-------------
| |X|O|
-------------
| |O| |
-------------
Player X, enter row (0, 1, 2): 2
Player X, enter column (0, 1, 2): 2
-------------
|X| | |
-------------
| |X|O|
-------------
| |O|X|
-------------
Player X wins!

pg. 12
LAB – 7

PROGRAM : Write a python program to remove stop words for a given passage from a text file
using NLTK?
CODE :
import nltk
from nltk.corpus import stopwords
nltk.download('stopwords')

def remove_stopwords(text):

stop_words = set(stopwords.words('english'))
words = nltk.word_tokenize(text)
filtered_words = [word for word in words if word.lower() not in stop_words]
filtered_text = ' '.join(filtered_words)
return filtered_text

with open('your_text_file.txt', 'r') as file:


text = file.read()

filtered_text = remove_stopwords(text)
print(filtered_text)

OUTPUT :
sample text file containing sentence demonstrating stop word removal . includes various parts speech
showcase filtering process .

pg. 13
LAB – 8

PROGRAM : Write a python program to implement stemming for a given sentence using
NLTK?
CODE :
import nltk
from nltk.stem import PorterStemmer

def stem_sentence(sentence):

stemmer = PorterStemmer()
words = nltk.word_tokenize(sentence)
stemmed_words = [stemmer.stem(word) for word in words]
stemmed_sentence = ' '.join(stemmed_words)
return stemmed_sentence

sentence = "The quick brown fox jumps over the lazy dog"
stemmed_sentence = stem_sentence(sentence)
print(stemmed_sentence)
OUTPUT :
the quick brown fox jump over the lazi dog

pg. 14
LAB – 9

PROGRAM : Write a python program to POS (Parts of Speech) tagging for the give sentence
using NLTK?
CODE :
import nltk

# Input sentence
sentence = "Natural Language Processing enables machines to understand human language."

tokens = nltk.word_tokenize(sentence)

pos_tags = nltk.pos_tag(tokens)

# Display the results


print("Tokens and their POS tags:")
for token, tag in pos_tags:
print(f"{token}: {tag}")

OUTPUT :
Tokens and their POS tags:
Natural: JJ
Language: NNP
Processing: NNP
enables: VBZ
machines: NNS
to: TO
understand: VB
human: JJ
language: NN
.: .

pg. 15
LAB – 10

PROGRAM : Write a python program to implement Lemmatization using NLTK?


CODE :
import nltk
from nltk.stem import WordNetLemmatizer

nltk.download('wordnet')
nltk.download('omw-1.4')

lemmatizer = WordNetLemmatizer()

def lemmatize_words(words):
lemmatized_words = []
for word in words:
lemmatized_word = lemmatizer.lemmatize(word)
lemmatized_words.append(lemmatized_word)
return lemmatized_words

words = ["running", "ran", "better", "cats", "geese", "feet", "mice"]

lemmatized_words = lemmatize_words(words)

print("Original words:", words)


print("Lemmatized words:", lemmatized_words)

OUTPUT :
Original words: ['running', 'ran', 'better', 'cats', 'geese', 'feet', 'mice']
Lemmatized words: ['running', 'ran', 'better', 'cat', 'goose', 'foot', 'mouse']

pg. 16

You might also like