0% found this document useful (0 votes)
14 views18 pages

Ai Lab Record

The document outlines a series of programming exercises completed over seven weeks, focusing on various AI and algorithm implementations in Python. Key projects include generating calendars, building a vacuum cleaner agent, solving the water jug problem, implementing the A* algorithm, creating a Sudoku solver, applying alpha-beta pruning, and designing an elevator planning system using STRIPS. Each week features specific aims, code examples, and outputs demonstrating the functionality of the programs.

Uploaded by

322103383011
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views18 pages

Ai Lab Record

The document outlines a series of programming exercises completed over seven weeks, focusing on various AI and algorithm implementations in Python. Key projects include generating calendars, building a vacuum cleaner agent, solving the water jug problem, implementing the A* algorithm, creating a Sudoku solver, applying alpha-beta pruning, and designing an elevator planning system using STRIPS. Each week features specific aims, code examples, and outputs demonstrating the functionality of the programs.

Uploaded by

322103383011
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

1

WEEK 1
Aim: To write a python program to generate calendar for given month and year and to implement simple
calculator.
Program:
#calendar
import calendar
year = int (input("Enter the year:"))
month = int (input("Entere the month (1-12):"))
if(month<1 or month>12):
print("Enter the valid month:")
else:
cal =calendar.month(year,month)
print("Calendar for {}-{}".format(year,month))
print(cal)

#calculator

import math
num1 = int(input())
num2 = int(input())
operation = input()
if(operation == '+'):
print('addition {}'.format(num1+num2))
elif (operation == '-'):
print('subtraction {}'.format(num1-num2))
elif (operation == '*'):
print('multiplication {}'.format(num1*num2))
elif (operation == '/'):
print('division {}'.format(num1//num2))
elif (operation == '%'):
print ('remainder{}'.format(num1 % num2))
else:
print('Enter correct operation :)')

Output:

#calendar

Enter the year:2004


Entere the month (1-12):11
Calendar for 2004-11

Name: B.Gayathri
322103383011
2

November 2004
Mo Tu We Th Fr Sa Su
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30

#calculator

PS D:\MYcodes\AI_lab> & C:/Python312/python.exe d:/MYcodes/AI_lab/week1.py


5
6
*
multiplication 30

Name: B.Gayathri
322103383011
3

WEEK 2
Aim: Design an intelligent system using python.
Program: ## vacuum cleaner
# Agent table defining actions based on state and location
agent_table = {
('Clean', 'A'): 'MoveRight',
('Clean', 'B'): 'MoveLeft',
('Dirty', 'A'): 'Suck',
('Dirty', 'B'): 'Suck',
}

# Vacuum Cleaner class


class VacuumCleaner:
def init (self, location='B', status='Dirty'): # Corrected init method
self.location = location
self.status = status

def percept(self):
return (self.status, self.location) # Returns both status and location as percept

def act(self, action):


if action == 'MoveRight':
self.location = 'B'
elif action == 'MoveLeft':
self.location = 'A'
elif action == "Suck":
self.status = 'Clean'

# Table-driven agent function


def table_driven_agent(percept):
return agent_table.get(percept, 'NoOp')

# Main Simulation loop


if name == " main ": # Corrected the name syntax
vacuum = VacuumCleaner()
for _ in range(5): # Loop for 5 iterations
current_percept = vacuum.percept()
action = table_driven_agent(current_percept)
print(f"Percept: {current_percept}, Action: {action}")
if action != 'NoOp':
vacuum.act(action)
print(f"Location: {vacuum.location}, Status: {vacuum.status}\n")

Name: B.Gayathri
322103383011
4

Output:
PS D:\MYcodes\AI_lab> & C:/Python312/python.exe d:/MYcodes/AI_lab/week2.py
Percept: ('Dirty', 'B'), Action: Suck
Location: B, Status: Clean

Percept: ('Clean', 'B'), Action: MoveLeft


Location: A, Status: Clean

Percept: ('Clean', 'A'), Action: MoveRight


Location: B, Status: Clean

Percept: ('Clean', 'B'), Action: MoveLeft


Location: A, Status: Clean

Percept: ('Clean', 'A'), Action: MoveRight


Location: B, Status: Clean

Name: B.Gayathri
322103383011
5

WEEK 3
Aim: Implement a production system and design a solution for a real world AI problem
Program: ##water-jug problem
def waterJugProblem (jug1Cap, jug2Cap, targetAmount):
j1 = j2= 0
actions = [("fill",1),("fill",2),("empty",1),("empty",2),("pour",1,2),("pour",2,1)]

##create an empty set to store visited sets.


visited = set()

##create a queue to store states to visit.


queue=[(j1,j2,[])]

while queue:
#Dequeue the front state from the queue
j1, j2, seq = queue.pop(0)
# If the state has not been visited before mark it as visited
if (j1,j2) not in visited:
visited.add((j1,j2))
## If this state matches the target amount, return sequence of actions taken to get this state
if j1 == targetAmount or j2 == targetAmount:
return seq
## generate all possible next states from this state
for action in actions:
if action[0]=="fill":
if action[1]==1:
next_state = (jug1Cap,j2)
else:
next_state = (j1,jug2Cap)
elif action [0]=="empty":
if action[1]==1:
next_state = (0,j2)
else:
next_state = (j1,0)
else:
if action[1]==1:
amount = min(j1,jug2Cap-j2)
next_state = (j1-amount,j2+amount)
else:
amount = min(j2,jug1Cap-j1)
next_state = (j1+amount,j2-amount)
## Add next_state to the queue if it has not been visited before
if next_state not in visited:
next_seq = seq+[action]
queue.append((next_state[0],next_state[1],next_seq))
Name: B.Gayathri
322103383011
6

## if queue becomes empty without finding a solution


return None

## Example usage
result = waterJugProblem(4,3,2)
print(result)

Output:
PS D:\MYcodes\AI_lab> & C:/Python312/python.exe d:/MYcodes/AI_lab/week3.py
[('fill', 2), ('pour', 2, 1), ('fill', 2), ('pour', 2, 1)]

Name: B.Gayathri
322103383011
7

WEEK 4
Aim: Implement A* algorithm.
Program: ## A* search
from heapq import heappush, heappop

def a_star_search(graph, start, goal, heuristic):


# Priority queue to store (cost, current_node, path)
open_list = []
heappush(open_list, (0, start, [start]))

# Cost from start to each node


g_cost = {start: 0}

while open_list:
# Get the node with the lowest f-cost
f_cost, current, path = heappop(open_list)

# If we reached the goal, return the path and cost


if current == goal:
return path, g_cost[current]

# Explore neighbors
for neighbor, weight in graph[current]:
tentative_g_cost = g_cost[current] + weight

# If this path is better, record it


if neighbor not in g_cost or tentative_g_cost < g_cost[neighbor]:
g_cost[neighbor] = tentative_g_cost
f_cost = tentative_g_cost + heuristic[neighbor]
heappush(open_list, (f_cost, neighbor, path + [neighbor]))

return None, float('inf') # No path found

# Example usage
if name == " main ":
# Define the graph as an adjacency list
graph = {
'A': [('B', 4), ('C', 2)],
'B': [('D', 4), ('E', 1)],
'C': [('E', 5)],
'D': [('F', 1)],
'E': [('F', 4)],
'F': []
}

Name: B.Gayathri
322103383011
8

# Define the heuristic for each node


heuristic = {
'A': 7,
'B': 5,
'C': 4,
'D': 3,
'E': 2,
'F': 0
}

start_node = 'A'
goal_node = 'F'

path, cost = a_star_search(graph, start_node, goal_node, heuristic)

if path:
print(f"Path found: {path} with cost: {cost}")
else:
print("No path found.")

Output:
PS D:\MYcodes\AI_lab> & C:/Python312/python.exe d:/MYcodes/AI_lab/week4.py
Path found: ['A', 'B', 'E', 'F'] with cost: 9

Name: B.Gayathri
322103383011
9

WEEK 5
Aim: Implement a Constraint specific problem.
Program: ##Sudoku game
puzzle = [
[8, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 3, 6, 0, 0, 0, 0, 0],
[0, 7, 0, 0, 9, 0, 2, 0, 0],
[0, 5, 0, 0, 0, 7, 0, 0, 0],
[0, 0, 0, 0, 4, 5, 7, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 3, 0],
[0, 0, 1, 0, 0, 0, 0, 6, 8],
[0, 0, 8, 5, 0, 0, 0, 1, 0],
[0, 9, 0, 0, 0, 0, 4, 0, 0]
]

def print_sudoku_puzzle(puzzle):
for i in range(9):
if (i % 3 == 0) and (i != 0):
print(" --------------------- ")
for j in range(9):
if (j % 3 == 0) and (j != 0):
print("| ", end="")
print(puzzle[i][j], end=" ")
print()

print_sudoku_puzzle(puzzle)

class CSP:
def init (self, variables, domains, constraints):
self.variables = variables
self.domains = domains
self.constraints = constraints
self.solution = None

def solve(self):
assignment = {}
self.solution = self.backtrack(assignment)
return self.solution

def backtrack(self, assignment):


if len(assignment) == len(self.variables):
return assignment

var = self.select_unassigned_variable(assignment)
for value in self.order_domain_values(var, assignment):
Name: B.Gayathri
322103383011
10

if self.is_consistent(var, value, assignment):


assignment[var] = value
result = self.backtrack(assignment)
if result is not None:
return result
del assignment[var]
return None

def select_unassigned_variable(self, assignment):


unassigned_vars = [var for var in self.variables if var not in assignment]
return min(unassigned_vars, key=lambda var: len(self.domains[var]))

def order_domain_values(self, var, assignment):


return self.domains[var]

def is_consistent(self, var, value, assignment):


for constraint_var in self.constraints[var]:
if constraint_var in assignment and assignment[constraint_var] == value:
return False
return True

variables = [(i, j) for i in range(9) for j in range(9)]


domains = {var: set(range(1, 10)) if puzzle[var[0]][var[1]] == 0 else {puzzle[var[0]][var[1]]} for var in
variables}

constraints = {}
def add_constraint(var):
constraints[var] = []
for i in range(9):
if i != var[0]:
constraints[var].append((i, var[1]))
if i != var[1]:
constraints[var].append((var[0], i))
sub_i, sub_j = var[0] // 3, var[1] // 3
for i in range(sub_i * 3, (sub_i + 1) * 3):
for j in range(sub_j * 3, (sub_j + 1) * 3):
if (i, j) != var:
constraints[var].append((i, j))

for i in range(9):
for j in range(9):
add_constraint((i, j))

print("*" * 7, "Solution", "*" * 7)


csp = CSP(variables, domains, constraints)
sol = csp.solve()

Name:B.Gayathri
322103383011
11

solution = [[0 for _ in range(9)] for _ in range(9)]


if sol:
for (i, j) in sol:
solution[i][j] = sol[(i, j)]
print_sudoku_puzzle(solution)
else:
print("No solution exists.")

Output:

PS D:\MYcodes\AI_lab> & C:/Python312/python.exe d:/MYcodes/AI_lab/week5.py


800|000|000
003|600|000
070|090|200
-------------
050|007|000
000|045|700
000|100|030
-------------
001|000|068
008|500|010
090|000|400

******* Solution *******


812|753|649
943|682|175
675|491|283
-------------
154|237|896
369|845|721
287|169|534
-------------
521|974|368
438|526|917
796|318|452

Name:B.Gayathri
322103383011
12

WEEK 6
Aim: Implement alpha-beta pruning
Program: ## alpha-beta pruning
MAX, MIN = 1000, -1000
def minimax(depth, nodeIndex, maximizingPlayer, values, alpha, beta):

if depth == 3:
return values[nodeIndex]

if maximizingPlayer:
best = MIN
for i in range(0, 2):
val = minimax(depth + 1, nodeIndex * 2 + i, False, values, alpha, beta)
best = max(best, val)
alpha = max(alpha, best)
if beta <= alpha:
break

return best
else:
best = MAX

for i in range(0, 2):


val = minimax(depth + 1, nodeIndex * 2 + i, True, values, alpha, beta)
best = min(best, val)
beta = min(beta, best)
if beta <= alpha:
break

return best

# Driver Code
if name == " main ":
values = [3, 5, 6, 9, 1, 2, 0, -1]
print("The optimal value is :", minimax(0, 0, True, values, MIN, MAX))

Output:
PS D:\MYcodes\AI_lab> & C:/Python312/python.exe d:/MYcodes/AI_lab/week6.py
The optimal value is : 5

Name:B.Gayathri
322103383011
13

WEEK 7
Aim: Design a planning system using STRIPS.
Program: ##Elevator
import random
import time

class Building:
def init (self, floors, customers):
self.number_of_floors = floors
self.customer_list = [Customer(i, floors) for i in range(1, customers + 1)]
self.customer_list.sort(key=lambda x: x.current_floor)
self.elevator = Elevator(floors, self.customer_list)
self.run()

def run(self):
print("ELEVATOR IS NOW STARTING")
print(f"There are {len(self.customer_list)} customers in the building")
self.output()

def output(self):
for customer in self.customer_list:
print(f"Customer {customer.customerID} is on floor {customer.current_floor} and wants to go to
{customer.destination_floor}")
self.move_elevator()

def move_elevator(self):
# Elevator moves up until it reaches the top floor
while self.elevator.current_floor < self.elevator.number_of_floors:
self.elevator.current_floor += 1
print(f"ELEVATOR MOVING UP - FLOOR {self.elevator.current_floor}")
self.handle_customers(1)
time.sleep(1) # Optional delay for simulation
# Then moves down until it reaches the first floor
while self.elevator.current_floor > 1:
self.elevator.current_floor -= 1
print(f"ELEVATOR MOVING DOWN - FLOOR {self.elevator.current_floor}")
self.handle_customers(-1)
time.sleep(1)
print("Elevator run is done!")

def handle_customers(self, direction):


# Copy the list to avoid modifying it during iteration
for customer in self.customer_list[:]:
if self.elevator.current_floor == customer.current_floor and customer.customer_direction ==
direction:
Name:B.Gayathri
322103383011
14

customer.in_elevator = True
print(f"Customer {customer.customerID} has entered the lift")
if customer.in_elevator and self.elevator.current_floor == customer.destination_floor:
customer.in_elevator = False
self.customer_list.remove(customer)
print(f"Customer {customer.customerID} has reached their destination")

class Elevator:
def init (self, floors, register_list):
self.number_of_floors = floors
self.current_floor = 0
self.register_list = register_list

class Customer:
def init (self, customerID, floors):
self.customerID = customerID
self.current_floor = random.randint(1, floors)
self.destination_floor = random.randint(1, floors)
# Ensure destination floor is different from current floor
while self.destination_floor == self.current_floor:
self.destination_floor = random.randint(1, floors)
self.customer_direction = 1 if self.current_floor < self.destination_floor else -1
self.in_elevator = False

def main():
try:
floors = int(input("Enter the number of floors: "))
customers = int(input("Enter number of customers: "))
Building(floors, customers)
except ValueError:
print("Invalid input. Please enter a number.")
main()

if name == " main ":


main()

Output:

PS D:\MYcodes\AI_lab> & C:/Python312/python.exe d:/MYcodes/AI_lab/week7.py


Enter the number of floors: 5
Enter number of customers: 10
ELEVATOR IS NOW STARTING
There are 10 customers in the building
Customer 3 is on floor 1 and wants to go to 3
Customer 6 is on floor 1 and wants to go to 2
Customer 9 is on floor 1 and wants to go to 3
Customer 2 is on floor 2 and wants to go to 4
Name:B.Gayathri
322103383011
15

Customer 5 is on floor 2 and wants to go to 5


Customer 4 is on floor 3 and wants to go to 2
Customer 7 is on floor 3 and wants to go to 4
Customer 10 is on floor 4 and wants to go to 5
Customer 1 is on floor 5 and wants to go to 1
Customer 8 is on floor 5 and wants to go to 2
ELEVATOR MOVING UP - FLOOR 1
Customer 3 has entered the lift
Customer 6 has entered the lift
Customer 9 has entered the lift
ELEVATOR MOVING UP - FLOOR 2
Customer 6 has reached their destination
Customer 2 has entered the lift
Customer 5 has entered the lift
ELEVATOR MOVING UP - FLOOR 3
Customer 3 has reached their destination
Customer 9 has reached their destination
Customer 7 has entered the lift
ELEVATOR MOVING UP - FLOOR 4
Customer 2 has reached their destination
Customer 7 has reached their destination
Customer 10 has entered the lift
ELEVATOR MOVING UP - FLOOR 5
Customer 5 has reached their destination
Customer 10 has reached their destination
ELEVATOR MOVING DOWN - FLOOR 4
ELEVATOR MOVING DOWN - FLOOR 3
Customer 4 has entered the lift
ELEVATOR MOVING DOWN - FLOOR 2
Customer 4 has reached their destination
ELEVATOR MOVING DOWN - FLOOR 1
Elevator run is done!

Name:B.Gayathri
322103383011
16

WEEK 8
Aim: Implement single neural network and test for different logic gates

Program: ##neural network

import numpy as np
import matplotlib.pyplot as plt

# Sigmoid Function
def sigmoid(z):
return 1 / (1 + np.exp(-z))

# Initialize neural network parameters


def initialize_parameters(input_features, hidden_neurons, output_features):
W1 = np.random.randn(hidden_neurons, input_features)
W2 = np.random.randn(output_features, hidden_neurons)
b1 = np.zeros((hidden_neurons, 1))
b2 = np.zeros((output_features, 1))
return {"W1": W1, "b1": b1, "W2": W2, "b2": b2}

# Forward Propagation
def forward_propagation(X, Y, parameters):
W1, W2 = parameters["W1"], parameters["W2"]
b1, b2 = parameters["b1"], parameters["b2"]

Z1 = np.dot(W1, X) + b1
A1 = sigmoid(Z1)
Z2 = np.dot(W2, A1) + b2
A2 = sigmoid(Z2)

logprobs = np.multiply(np.log(A2), Y) + np.multiply(np.log(1 - A2), (1 - Y))


cost = -np.sum(logprobs) / X.shape[1]

return cost, (Z1, A1, W1, b1, Z2, A2, W2, b2), A2

# Backward Propagation
def backward_propagation(X, Y, cache):
Z1, A1, W1, b1, Z2, A2, W2, b2 = cache
m = X.shape[1]

dZ2 = A2 - Y
dW2 = np.dot(dZ2, A1.T) / m
db2 = np.sum(dZ2, axis=1, keepdims=True) / m
dA1 = np.dot(W2.T, dZ2)
dZ1 = dA1 * (A1 * (1 - A1))
dW1 = np.dot(dZ1, X.T) / m
Name:B.Gayathri
322103383011
17

db1 = np.sum(dZ1, axis=1, keepdims=True) / m

return {"dW1": dW1, "db1": db1, "dW2": dW2, "db2": db2}

# Update Parameters
def update_parameters(parameters, gradients, learning_rate):
for key in parameters:
parameters[key] -= learning_rate * gradients["d" + key]
return parameters

# Training Model for AND Gate


X = np.array([[0, 0, 1, 1], [0, 1, 0, 1]])
Y = np.array([[0, 0, 0, 1]])

hidden_neurons = 2
parameters = initialize_parameters(X.shape[0], hidden_neurons, Y.shape[0])
epochs = 100000
learning_rate = 0.01
losses = np.zeros((epochs, 1))

for i in range(epochs):
losses[i, 0], cache, A2 = forward_propagation(X, Y, parameters)
gradients = backward_propagation(X, Y, cache)
parameters = update_parameters(parameters, gradients, learning_rate)

plt.plot(losses)
plt.xlabel("Epochs")
plt.ylabel("Loss")
plt.show()

# Testing
X_test = np.array([[1, 1, 0, 0], [0, 1, 0, 1]])
cost, _, A2 = forward_propagation(X_test, Y, parameters)
prediction = (A2 > 0.5) * 1.0
print(prediction)

Output:
PS D:\MYcodes\AI_lab> & C:/Python312/python.exe d:/MYcodes/AI_lab/week8.py
[[0. 1. 0. 0.]]

Name:B.Gayathri
322103383011
18

Name:B.Gayathri
322103383011

You might also like