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.")
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
def heuristic(a, b): return abs(a[0] - b[0]) + abs(a[1] - b[1])
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],
]
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")
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.")
# 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)
}
# 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()
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 required libraries
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
print(f"\nAccuracy: {accuracy}")
print("\nClassification Report:")
print(report)
8. Use the Naïve Bayes classifier to classify the dataset.
# Import required libraries
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
from sklearn.metrics import accuracy_score, classification_report
print(f"\nAccuracy: {accuracy}")
print("\nClassification Report:")
print(report)
9. Implement K-Means clustering Algorithm.
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import make_blobs