Lab Programs
Lab Programs
1. Write a program to solve the Water Jug Problem using Breadth Frist Search
(BFS).
from collections import deque
while queue:
jug1, jug2 = queue.popleft()
if jug1 == target or jug2 == target:
return True
next_states = [
(jug1_max, jug2), # Fill Jug 1
(jug1, jug2_max), # Fill Jug 2
(0, jug2), # Empty Jug 1
(jug1, 0), # Empty Jug 2
(jug1 - min(jug1, jug2_max - jug2), jug2 + min(jug1, jug2_max - jug2)), #
Pour Jug 1 to Jug 2
(jug1 + min(jug2, jug1_max - jug1), jug2 - min(jug2, jug1_max - jug1)) #
Pour Jug 2 to Jug 1
]
return False
# Example usage:
jug1_capacity, jug2_capacity, target_amount = 5, 10, 2
result = bfs_water_jug(jug1_capacity, jug2_capacity, target_amount)
print(f"{'Possible' if result else 'Not possible'} to measure {target_amount} liters
using the given jugs.")
output:
2. Write a program to find the optimum path from Source to Destination using A *
search technique.
import heapq
class Node:
def __init__(self, position, parent=None, g=0, h=0):
self.position, self.parent = position, parent
self.g, self.h = g, h
self.f = g + h
def __lt__(self, other): return self.f < other.f
while open_list:
current = heapq.heappop(open_list)
if current.position == end:
path = []
while current: path.append(current.position); current = current.parent
return path[::-1]
closed_list.add(current.position)
for dx, dy in [(0, -1), (0, 1), (-1, 0), (1, 0)]:
pos = (current.position[0] + dx, current.position[1] + dy)
if (0 <= pos[0] < len(grid) and 0 <= pos[1] < len(grid[0]) and
grid[pos[0]][pos[1]] == 0 and pos not in closed_list):
new_node = Node(pos, current, current.g + 1, heuristic(pos, end))
if not any(n.position == new_node.position and n.f <= new_node.f for n in
open_list):
heapq.heappush(open_list, new_node)
return None
# Example usage
grid = [
[0, 1, 0, 0, 0, 0],
[0, 1, 0, 1, 1, 0],
[0, 0, 0, 0, 1, 0],
[0, 1, 1, 0, 1, 0],
[0, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
]
output:
def solve_n_queens(n):
board = [[0] * n for _ in range(n)]
if solve_n_queens_util(board, 0): print_board(board)
else: print("Solution does not exist")
def print_board(board):
print("\n".join(" ".join("Q" if col else "." for col in row) for row in board) + "\n")
output:
def print_board(board):
print("\n".join(" | ".join(row) for row in board) + "\n" + "-" * 9)
def best_move(board):
best_score, move = -math.inf, None
for i in range(3):
for j in range(3):
if board[i][j] == ' ':
board[i][j] = 'X'
score = minimax(board, False)
board[i][j] = ' '
if score > best_score:
best_score, move = score, (i, j)
return move
def play_game():
board = [[' ']*3 for _ in range(3)]
print("Initial Board:")
print_board(board)
while True:
move = best_move(board)
if move:
board[move[0]][move[1]] = 'X'
print("\nAI (X) makes a move:")
print_board(board)
if check_winner(board, 'X'):
print("X wins!")
break
if all(cell in ['X', 'O'] for row in board for cell in row):
print("It's a draw!")
break
try:
row, col = map(int, input("Enter your move (row col): ").split())
if board[row][col] == ' ':
board[row][col] = 'O'
print("\nYou (O) make a move:")
print_board(board)
if check_winner(board, 'O'):
print("O wins!")
break
else:
print("Cell occupied! Try again.")
except (ValueError, IndexError):
print("Invalid input! Enter row and column as 0, 1, or 2.")
5. Using OpenCV python library capture an image and perform the following image
processing operations:
a) Image Resizing
b) Blurring of Image
c) Gray scaling of image
d) Scaling and rotation
e) Edge Detection
f) Segmentation using thresholding
g) Background subtraction
h) Morphological operations
import cv2
import numpy as np
import matplotlib.pyplot as plt
# Load image
image_path = 'ntr.jpg'
image = cv2.imread(image_path)
if image is None:
print("Failed to load image.")
else:
transformations = {
"Resized Image": cv2.resize(image, (300, 300)),
"Blurred Image": cv2.GaussianBlur(image, (15, 15), 0),
"Gray Scale Image": cv2.cvtColor(image, cv2.COLOR_BGR2GRAY),
"Scaled Image": cv2.resize(image, None, fx=0.5, fy=0.5),
"Rotated Image": cv2.warpAffine(image, cv2.getRotationMatrix2D((image.shape[1]//2,
image.shape[0]//2), 45, 1.0), (image.shape[1], image.shape[0])),
"Edge Detection": cv2.Canny(image, 100, 200),
"Thresholded Image": cv2.threshold(cv2.cvtColor(image, cv2.COLOR_BGR2GRAY),
128, 255, cv2.THRESH_BINARY)[1],
"Background Subtraction": cv2.createBackgroundSubtractorMOG2().apply(image)
}
output:
6. Write a program with two menu options 1) Capture Image and 2) Recognize
Image. This program should capture pictures of five students and save them.
The program should identify/recognize the student and display the student's
name.
import cv2
import numpy as np
import os
from tensorflow.keras.applications.mobilenet_v2 import MobileNetV2,
preprocess_input
from tensorflow.keras.preprocessing.image import img_to_array, load_img
from tensorflow.keras.models import Model
from sklearn.preprocessing import LabelEncoder
from sklearn.svm import SVC
import pickle
import time # For delays if needed
# List of students
students_list = ["Aaa", "Bbb", "Ccc", "Ddd", "Eee"]
# Menu options
def menu():
print("1. Capture Images of Students")
print("2. Recognize Student")
print("3. Exit")
return int(input("Choose an option: "))
# Main program
def main():
while True:
choice = menu()
if choice == 1:
capture_images(students_list)
train_recognizer(students_list)
elif choice == 2:
recognize_student()
elif choice == 3:
print("Exiting the program.")
break
else:
print("Invalid option. Please try again.")
if __name__ == "__main__":
main()
output:
Using Keras/any standard dataset write the program for the following Machine
learning takes:
7. use the decision tree classifier to classify the dataset.
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score, classification_report
output:
output:
9. Implement K-Means clustering Algorithm.
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import make_blobs
from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler
output:
10. Using Python NLTK, perform the following Natural Language Processing (NLP)
tasks for any textual content.
a) Tokenizing
b) Filtering Stop Words
c) Stemming
d) Part of Speech tagging
e) Chunking
f) Named Entity Recognition (NER)
import nltk
nltk.download('punkt_tab')
nltk.download()
import nltk
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords
from nltk.stem import PorterStemmer
from nltk import pos_tag, ne_chunk
# Sample text
text = "The quick brown fox jumps over the lazy dog. Natural Language Processing is fun!"
# Outputs
print("Tokens:", tokens)
print("Filtered tokens:", filtered_tokens)
print("Part-of-Speech tags:", pos_tags)
print("Named Entities:", [(chunk.label(), ' '.join(c[0] for c in chunk)) for chunk in
chunked_text if hasattr(chunk, 'label')])
output:
11. Write a program that uses Neural networks for image classification using Keras Iris
dataset.
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
# Assuming X_train, y_train, X_test, y_test are already loaded from the notebook
# Make predictions
predictions = model.predict(X_test)
predicted_classes = [tf.argmax(pred).numpy() for pred in predictions]
print('Predicted classes:', predicted_classes)
output: