Ai Lab Record
Ai Lab Record
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
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
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',
}
def percept(self):
return (self.status, self.location) # Returns both status and location as percept
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
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)]
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
## 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
while open_list:
# Get the node with the lowest f-cost
f_cost, current, path = heappop(open_list)
# Explore neighbors
for neighbor, weight in graph[current]:
tentative_g_cost = g_cost[current] + weight
# 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
start_node = 'A'
goal_node = 'F'
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
var = self.select_unassigned_variable(assignment)
for value in self.order_domain_values(var, assignment):
Name: B.Gayathri
322103383011
10
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))
Name:B.Gayathri
322103383011
11
Output:
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
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!")
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()
Output:
Name:B.Gayathri
322103383011
16
WEEK 8
Aim: Implement single neural network and test for different logic gates
import numpy as np
import matplotlib.pyplot as plt
# Sigmoid Function
def sigmoid(z):
return 1 / (1 + np.exp(-z))
# 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)
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
# Update Parameters
def update_parameters(parameters, gradients, learning_rate):
for key in parameters:
parameters[key] -= learning_rate * gradients["d" + key]
return parameters
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