0% found this document useful (0 votes)
3 views16 pages

AIML LAB EXPS

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 16

#PASSWORD GENERATION

print("===Welcome to the signIn and logIn page===")


user_data={}

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=" ")

for neighbor in graph[node]:


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

# Example usage
graph = {
1: [2, 3],
2: [4, 5],
3: [6],
4: [],
5: [6],
6: []
}
bfs(graph, 1)

# DFS USING GRAPH


def dfs(graph, node, visited=set()):
if node not in visited:
print(node, end=" ")
visited.add(node)
for neighbor in graph[node]:
dfs(graph, neighbor, visited)

# 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})")

return True, moves

def gcd(x, y):


while y:
x, y = y, x % y
return x

# Example with 4-liter and 3-liter jugs, target is 2 liters


reachable, steps = water_jug_problem(4, 3, 2)

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

def a_star(graph, start, goal):


open_set = [(0, start)]
came_from = {}
cost = {start: 0}

while open_set:
_, current = heappop(open_set)
if current == goal:
path = []
while current:
path.append(current)
current = came_from.get(current)
return path[::-1]

for neighbor, weight in graph.get(current, []):


new_cost = cost[current] + weight
if new_cost < cost.get(neighbor, float('inf')):
cost[neighbor] = new_cost
heappush(open_set, (new_cost, neighbor))
came_from[neighbor] = current

return None

graph = {
'A': [('B', 1), ('C', 3)],
'B': [('D', 1), ('E', 5)],
'C': [('E', 2)],
'D': [('F', 4)],
'E': [('F', 1)],
'F': []
}

print("Path:", a_star(graph, 'A', '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']

# Iterate over rows in the CSV


for i in cr:
if h == ['0', '0', '0', '0'] and i[-1] == 'YES':
h=i
if i[-1] == 'YES': # Compare only for 'YES' class
for j in range(len(i) - 1):
if h[j] != i[j]:
h[j] = '?'
print(h)
co.close()

#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

for example in data:


# If the example is positive
if example[-1] == 'YES':
for i in range(len(S)):
if S[i] != example[i]:
S[i] = '?' # Generalize
G = [g for g in G if all(x == '?' or x == g[i] for i, x in
enumerate(example[:-1]))]

# If the example is negative


else:
G = [g for g in G if not all(g[i] == example[i] or g[i] == '?'
for i in range(len(example)-1))]
for i in range(len(S)):
if S[i] != example[i]:
S[i] = '?' # Generalize

return S, G

# Example data (features and label: YES for positive and NO


for negative)
data = [
['sunny', 'warm', 'high', 'FALSE', 'YES'],
['sunny', 'warm', 'high', 'TRUE', 'NO'],
['rainy', 'cold', 'high', 'FALSE', 'YES'],
['sunny', 'warm', 'high', 'TRUE', 'YES']
]
S, G = candidate_elimination(data)
print("Most specific hypothesis (S):", S)
print("Most general hypothesis (G):", 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

# Load the Wine dataset


wine = load_wine()
X = wine.data # Features
y = wine.target # Target labels

# Split the dataset into training and testing sets


X_train, X_test, y_train, y_test = train_test_split(X, y,
test_size=0.3, random_state=42)

# Apply Naive Bayes


nb = GaussianNB()
nb.fit(X_train, y_train)

# 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

# Split the dataset into training and testing sets


X_train, X_test, y_train, y_test = train_test_split(X, y,
test_size=0.3, random_state=42)

# 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

# Load the Iris dataset


iris = load_iris()
X = iris.data # Use all four features
y = iris.target # True labels (for reference, not used in
clustering)

# Apply KMeans
kmeans = KMeans(n_clusters=3, random_state=42)
kmeans.fit(X)
labels = kmeans.labels_

# Plotting (using first two features for simplicity)


plt.scatter(X[:, 0], X[:, 1],c=labels, cmap='viridis', s=30,
label='Data Points')
centroids = kmeans.cluster_centers_
plt.scatter(centroids[:, 0], centroids[:, 1], c='red', marker='x',
s=100, label='Centroids')
plt.legend()
plt.title("K-Means Clustering on Iris Dataset (First Two
Features)")
plt.xlabel(iris.feature_names[0])
plt.ylabel(iris.feature_names[1])
plt.show()

You might also like