AIML LAB EXPS
AIML LAB EXPS
AIML LAB EXPS
def signin():
username= input("Enter username:")
password= input("Enter Password:")
user_data[username]= password
print("SignIn Successful!")
def login():
username1= input("Enter username:")
password1= input("Enter password:")
if username1 in user_data:
if user_data[username1]== password1:
print("Login Successful!")
else:
print("Wrong Password!")
else:
print("Wrong username!")
signin()
login()
#BFS USING GRAPH
from collections import deque
def bfs(graph, start):
visited = set()
queue = deque([start])
visited.add(start)
while queue:
node = queue.popleft()
print(node, end=" ")
# Example usage
graph = {
1: [2, 3],
2: [4, 5],
3: [6],
4: [],
5: [6],
6: []
}
bfs(graph, 1)
# Example usage
graph = {
1: [2, 3],
2: [4, 5],
3: [6],
4: [],
5: [6],
6: []
}
dfs(graph, 1)
#WATER-JUG
def water_jug_problem(a, b, target):
# Check if the target is reachable using GCD
if target % gcd(a, b) != 0 or target > max(a, b):
return False, []
moves = []
x, y = 0, 0 # Initial state (both jugs are empty)
while x != target and y != target:
# Fill Jug A
if x == 0:
x=a
moves.append(f"Fill Jug A: ({x}, {y})")
# Fill Jug B
elif y == 0:
y=b
moves.append(f"Fill Jug B: ({x}, {y})")
# Pour from Jug A to Jug B
elif x > 0 and y < b:
pour = min(x, b - y)
x -= pour
y += pour
moves.append(f"Pour from Jug A to Jug B: ({x}, {y})")
# Pour from Jug B to Jug A
elif y > 0 and x < a:
pour = min(y, a - x)
y -= pour
x += pour
moves.append(f"Pour from Jug B to Jug A: ({x}, {y})")
if reachable:
print("Solution possible. Steps to reach the target:")
for step in steps:
print(step)
else:
print("Solution not possible.")
#VACCUUM CLEANER
def vacuum_cleaner(environment, start_pos):
pos = start_pos
for i in range(len(environment)):
if environment[pos] == "dirty":
print(f"Cleaning position {pos}")
environment[pos] = "clean"
print(f"Moving to position {(pos + 1) %
len(environment)}")
pos = (pos + 1) % len(environment)
print("All positions are clean!")
# Example usage
environment = ["dirty", "clean", "dirty", "dirty"] # Example
environment
start_pos = 0 # Starting position
vacuum_cleaner(environment, start_pos)
#A* SEARCH
from heapq import heappop, heappush
while open_set:
_, current = heappop(open_set)
if current == goal:
path = []
while current:
path.append(current)
current = came_from.get(current)
return path[::-1]
return None
graph = {
'A': [('B', 1), ('C', 3)],
'B': [('D', 1), ('E', 5)],
'C': [('E', 2)],
'D': [('F', 4)],
'E': [('F', 1)],
'F': []
}
# N-QUEEN
from itertools import permutations
def solve_nqueens(n):
for perm in permutations(range(n)):
if n == len(set(perm[i] + i for i in range(n))) ==
len(set(perm[i] - i for i in range(n))):
for i in perm:
print(". " * i + "Q " + ". " * (n - i - 1))
print()
solve_nqueens(4)
#FIND S
import csv
file_path =
r"C:\Users\faadi\OneDrive\Desktop\AIML\test.csv"
co = open(file_path, 'r')
cr = csv.reader(co)
# Initialize hypothesis
h = ['0', '0', '0', '0']
#CANDIDATE ELIMINATION
def candidate_elimination(data):
# Initialize the most specific hypothesis (S) and the most
general hypothesis (G)
S = ['0', '0', '0', '0'] # Specific boundary
G = [['?'] * len(data[0]) for _ in range(len(data[0]))] #
General boundary
return S, G
#NAIVE BAYES
from sklearn.datasets import load_wine
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
from sklearn.metrics import accuracy_score,
confusion_matrix, ConfusionMatrixDisplay
# Make predictions
y_pred = nb.predict(X_test)
# Print accuracy
accuracy = accuracy_score(y_test, y_pred)
print(f"Accuracy: {accuracy:.2f}")
# Confusion Matrix
cm = confusion_matrix(y_test, y_pred)
disp = ConfusionMatrixDisplay(confusion_matrix=cm,
display_labels=wine.target_names)
disp.plot()
#K-NEAREST ALGORITHM
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score,
confusion_matrix, ConfusionMatrixDisplay
# Load the Iris dataset
iris = load_iris()
X = iris.data # Features
y = iris.target # Target labels
# Apply k-NN
knn = KNeighborsClassifier(n_neighbors=3) # k=3
knn.fit(X_train, y_train)
# Make predictions
y_pred = knn.predict(X_test)
# Print accuracy
accuracy = accuracy_score(y_test, y_pred)
print(f"Accuracy: {accuracy:.2f}")
# Confusion Matrix
cm = confusion_matrix(y_test, y_pred)
disp = ConfusionMatrixDisplay(confusion_matrix=cm,
display_labels=iris.target_names)
disp.plot()
#K-MEANS
from sklearn.datasets import load_iris
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
import numpy as np
# Apply KMeans
kmeans = KMeans(n_clusters=3, random_state=42)
kmeans.fit(X)
labels = kmeans.labels_