800 AI Lab documentation final
800 AI Lab documentation final
March,2025.
1
Table of Contents
S.no Experiment Date
1 Python & Prolog 20-12-2024
2 Vaccum Cleaner 28-12-2024
3 Monkey Banana 03-01-2025
Problem
4 Water-Jug Problem 14-03-2025
2
VU22CSEN0100800 WEEK-1 Date: 20-12-2024
Task -1
Date: 20-12-2024
3
VU22CSEN0100800 WEEK-1 Date: 20-12-2024
Code:
4
VU22CSEN0100800 WEEK-1 Date: 20-12-2024
5
VU22CSEN0100800 WEEK-1 Date: 20-12-2024
Output:
6
VU22CSEN0100800 WEEK-1 Date: 20-12-2024
1B : Using Prolog
Question: Revisit/Refresh the Study of Python and PROLOG (can
use any other programming Language also).
7
VU22CSEN0100800 WEEK-1 Date: 20-12-2024
8
VU22CSEN0100800 WEEK-2 Date: 28-12-2024
Task-2
Question: Write a program to control the VACUUM Cleaner moves
(Intelligent systems design process).
Aim: The program aims to create an intelligent vacuum cleaner that autonomously
cleans two locations (A and B) using a rule-based system. It evaluates performance by
calculating the cost of cleaning (1 unit per clean) and movement (1 unit per move).
The vacuum decides actions based on the cleanliness of its current location and the
adjacent one. The goal is to ensure both locations are clean while displaying the
cleaning steps, final environment state, and total cost. This simple, rule-based design
promotes efficient decision-making and mimics basic intelligent behavior.
Description: The provided program simulates a simple intelligent agent: a vacuum
cleaner that autonomously cleans two rooms (A and B) based on their cleanliness status.
The vacuum uses a rule-based system to determine its actions, including cleaning the
current location and moving between rooms. The program evaluates its performance by
calculating the total cost of operations, including cleaning and movement.
Key Features:
1. Input Interaction:
○ The user inputs the vacuum's initial location (A or B).
○ The cleanliness status of both the initial room and the other room (0 for
clean, 1 for dirty) is provided.
2. Decision-Making Process:
○ If the current room is dirty, the vacuum cleans it, incurring a cost of 1
unit.
○ If the other room is dirty, the vacuum moves to it, incurring a movement
cost of 1 unit, and cleans it.
3. Performance Evaluation:
○ The program tracks the total cost incurred:
■ Cleaning cost: 1 unit per room cleaned.
■ Movement cost: 1 unit per transition between rooms.
○ The goal is to clean both rooms with minimal cost.
4. Output:
○ The sequence of actions taken by the vacuum cleaner.
○ The final state of both rooms after cleaning.
○ The total cost as a performance metric.
9
VU22CSEN0100800 WEEK-2 Date: 28-12-2024
5. Automation Simulation:
○ The program demonstrates basic automation, mimicking intelligent
decision-making in a controlled, rule-based environment.
CODE:
# initializing goal_state
cost = 0
10
VU22CSEN0100800 WEEK-2 Date: 28-12-2024
if location_input == 'A':
# Location A is Dirty.
if status_input == '1':
print("Location A is Dirty.")
goal_state['A'] = '0'
if status_input_complement == '1':
# if B is Dirty
print("Location B is Dirty.")
goal_state['B'] = '0'
else:
11
VU22CSEN0100800 WEEK-2 Date: 28-12-2024
if status_input == '0':
print("Location B is Dirty.")
goal_state['B'] = '0'
else:
print(cost)
else:
# Location B is Dirty.
if status_input == '1':
print("Location B is Dirty.")
goal_state['B'] = '0'
12
VU22CSEN0100800 WEEK-2 Date: 28-12-2024
if status_input_complement == '1':
# if A is Dirty
print("Location A is Dirty.")
goal_state['A'] = '0'
else:
print(cost)
print("Location A is Dirty.")
goal_state['A'] = '0'
13
VU22CSEN0100800 WEEK-2 Date: 28-12-2024
else:
# done cleaning
print(goal_state)
vacuum_world()
SAMPLE OUTPUT:
Enter Location of Vacuum: A
Location A is Dirty.
Location B is Dirty.
14
VU22CSEN0100800 WEEK-2 Date: 28-12-2024
GOAL STATE:
Performance Measurement: 3
15
VU22CSEN0100800 WEEK-3 Date: 03-01-2025
Task-3
Question: Write a program to solve Monkey & Banana Problem.
Aim: To implement a solution for the Monkey and Banana Problem using
Python, where the monkey must reach the banana by performing a sequence
of actions. The problem is solved using state-space search, demonstrating
how an agent (monkey) makes decisions to achieve a goal.
Description: The Monkey and Banana Problem is a classic AI planning
problem where a monkey must retrieve a banana that is hanging from the
ceiling. The challenge is that the monkey cannot reach the banana directly; it
must use a box to climb and grab the banana. This problem demonstrates
state-space search, goal-oriented behavior, and decision-making in AI.
Code:
16
VU22CSEN0100800 WEEK-3 Date: 03-01-2025
Output:
17
VU22CSEN0100800 WEEK-4 Date: 14-02-2025
Task-4
Question: You have three jugs with capacities of 8 liters, 5 liters, and 3 liters. The 8-
liter jug is full, and the other two are empty. How can you measure exactly 4 liters in
one of the jugs?
With jug capacities of 10 liters, 7 liters, and 4 liters, how can you get exactly 2 liters in
one of the jugs?
Aim: The Water Jug Problem aims to demonstrate and apply state-space search
techniques to solve a real-world-inspired problem using Artificial Intelligence (AI)
principles. Specifically, the objective is to find the shortest sequence of steps that leads
to a desired goal state, such as measuring an exact quantity of water using two or more
jugs of predefined capacities.
Description: The Water Jug Problem involves measuring a specific amount of water
using two jugs with predefined capacities. The problem is approached algorithmically
by modelling possible states of the jugs and using BFS to find the shortest sequence of
actions leading to the desired amount of water.
Code:
18
VU22CSEN0100800 WEEK-4 Date: 14-02-2025
import pygame
import time
# Initialize Pygame
pygame.init()
BLACK = (0, 0, 0)
# Set up display
screen.fill(WHITE)
19
VU22CSEN0100800 WEEK-4 Date: 14-02-2025
screen.blit(text, (x + 5, y + 10))
pygame.display.flip()
initial_state = (cap_a, 0, 0)
queue = deque([initial_state])
visited = set()
visited.add(initial_state)
while queue:
state = queue.popleft()
if goal in state:
return state
20
VU22CSEN0100800 WEEK-4 Date: 14-02-2025
next_states = [
visited.add(new_state)
queue.append(new_state)
def main():
running = True
solution = None
while running:
if event.type == pygame.QUIT:
running = False
if not solution:
time.sleep(3)
running = False
pygame.quit()
if solution:
print("Solution:", solution)
else:
if __name__ == "__main__":
main()
OUTPUT:
22
VU22CSEN0100800 WEEK-5 Date: 21-02-2025
Task-5a
123
456
78
123
4 6
758
23
VU22CSEN0100800 WEEK-5 Date: 21-02-2025
PYTHON CODE :
import heapq
def lowest_cost_first_search(graph, start, goal):
"""
Solves the shortest path problem using Lowest-Cost-First Search.
:param graph: Dictionary representing the graph as {node: [(neighbor, cost),
...]}.
:param start: Starting node.
:param goal: Goal node.
:return: Tuple of (shortest path, cost) or (None, float('inf')) if no path exists.
"""
# Priority queue to store (cost, current_node, path)
priority_queue = [(0, start, [start])]
visited = set() # To keep track of visited nodes
24
VU22CSEN0100800 WEEK-5 Date: 21-02-2025
while priority_queue:
current_cost, current_node, path = heapq.heappop(priority_queue)
# Skip already visited nodes
if current_node in visited:
continue
visited.add(current_node)
# Goal reached
if current_node == goal:
return path, current_cost
# Explore neighbors
for neighbor, cost in graph.get(current_node, []):
if neighbor not in visited:
heapq.heappush(priority_queue, (current_cost + cost, neighbor, path +
[neighbor]))
# If no path found
return None, float('inf')
# Graph from the image as adjacency list
graph = {
'C': [('B', 2), ('T', 1), ('O', 3), ('E', 2), ('P', 5)],
'B': [('A', 1), ('R', 4), ('S', 3)],
'O': [('I', 1), ('N', 2)],
'E': [('G', 5)],
'P': [('L', 5), ('F', 1), ('D', 3)],
'I': [('Z', 2)],
'A': [], 'R': [], 'S': [], 'N': [], 'G': [], 'L': [], 'F': [], 'D': [], 'Z': []
}
25
VU22CSEN0100800 WEEK-5 Date: 21-02-2025
OUTPUT :
26
VU22CSEN0100800 WEEK-5 Date: 21-02-2025
PYTHON CODE :
while queue:
if current_node == goal:
return path
visited.add(current_node)
return None
tree = {
27
VU22CSEN0100800 WEEK-5 Date: 21-02-2025
'E': [],
'G': [],
'H': []
start_node = 'A'
goal_node = 'H'
if shortest_path:
else:
OUTPUT :
3. 8 Puzzle problem
28
VU22CSEN0100800 WEEK-6 Date: 28-02-2025
Task-6
Date: 20-02-2025
Question: Write a program to solve shortest path problem: (i) Using BFS (ii) Using
Lowest-cost-first search.
Aim: The aim is to implement algorithms for finding the shortest path in a graph using
BFS and to create an AI for playing Tic-Tac-Toe using the minimax algorithm with
alpha-beta pruning.
Description: This part of the code implements the Breadth-First Search (BFS)
algorithm to find the shortest path between two nodes in an unweighted graph. The
graph is represented as an adjacency list, where each node is associated with a list of its
neighboring nodes. The bfs_shortest_path(graph, start, goal) function starts by adding
the start node to a queue and iteratively explores all possible paths from the start node.
It checks each node level by level and ensures that the shortest path (in terms of the
number of edges) is found. Once the goal node is reached, the function returns the path
from the start to the goal. If no path exists, it returns None. The algorithm ensures an
optimal solution for finding the shortest path in unweighted graphs.
Part(i):
from collections import deque
if start == goal:
return [start] # If start and goal are the same, return the path containing just the start
while queue:
path = queue.popleft() # Get the current path from the queue
node = path[-1] # The current node is the last element in the path
49
VU22CSEN0100800 WEEK-6 Date: 28-02-2025
if neighbor == goal:
return new_path # Return the path if the goal is found
visited.add(node) # Mark the node as visited
50
VU22CSEN0100800 WEEK-6 Date: 28-02-2025
Output
Part(ii):
Code:
import heapq
# Min-heap priority queue for processing nodes with the smallest distance
while queue:
if current_node == goal:
51
VU22CSEN0100800 WEEK-6 Date: 28-02-2025
path = []
path.append(current_node)
current_node = previous_nodes[current_node]
continue
# Explore neighbors
distances[neighbor] = distance
previous_nodes[neighbor] = current_node
# Input graph from user in the form of an adjacency list with weights
graph = {}
for _ in range(n):
neighbors = input(f"Enter neighbors and weights of {node} (format: neighbor1:weight, neighbor2:weight): ").split(',')
graph[node] = []
graph[node].append((neighbor_name.strip(), int(weight)))
52
VU22CSEN0100800 WEEK-6 Date: 28-02-2025
if path:
else:
Output:
53
VU22CSEN0100800 WEEK-7 Date: 02-03-2025
Task-7
Description: The Tic-Tac-Toe game, commonly played on a 3x3 grid, has the objective of getting
three of the same marks (either 'X' or 'O') in a row, column, or diagonal. Players take turns marking
empty spaces on the grid, and the first to align three marks wins the game. If all spaces are filled and
no player wins, the game results in a draw.
Step-by-Step Explanation:
1. Initialize Pygame: Set up the window and basic configurations.
2. Draw the grid: Use Pygame's drawing functions to draw the Tic-Tac-Toe grid.
3. Player input: Handle player clicks to place X's and O's on the grid.
4. Win conditions: Check for horizontal, vertical, or diagonal lines that match.
Code :
54
VU22CSEN0100800 WEEK-7 Date: 02-03-2025
Output:
55
VU22CSEN0100800 WEEK-8 Date: 17-03-2025
Task-8
Date: 17-03-2025
Question: Write a program to implement Hangman game (Or Wordle).
Aim: The aim of Hangman is to correctly guess the hidden word by selecting letters
within a limited number of attempts while avoiding too many incorrect guesses. Players
must use their vocabulary, spelling skills, and logical reasoning to figure out the word
before the hangman figure is completely drawn. Each incorrect guess results in a part of
the figure being added, bringing the player closer to losing the game. The challenge lies
in making strategic guesses, starting with common letters and using clues from
previously revealed letters to deduce the correct word before running out of chances.
Description: Hangman is a word-guessing game where a player attempts to uncover a hidden word
by guessing letters within a limited number of chances. The game typically begins with a blank
representation of the word, with each blank corresponding to a letter in the word. Players take turns
guessing letters, and if a guessed letter is in the word, it is revealed in its correct position. However, if
the guessed letter is incorrect, a part of a stick figure—representing the "hangman"—is drawn. The
game continues until the player either correctly identifies the word or exhausts all allowed incorrect
guesses, leading to a loss. This game is both educational and entertaining, helping players improve
their vocabulary, spelling, and logical thinking skills. Hangman is often played in classrooms, as a
casual pastime, or even in digital formats, making it widely accessible. Variations of the game include
themed versions where words belong to specific categories, such as movies, animals, or history. It can
be played by two or more players, with one person selecting the word while the others attempt to guess
it. The simplicity of the game, combined with the challenge of guessing words strategically, makes
Hangman a timeless and engaging activity for all ages.
Code:
56
VU22CSEN0100800 WEEK-8 Date: 17-03-2025
57
VU22CSEN0100800 WEEK-8 Date: 17-03-2025
58
VU22CSEN0100800 WEEK-8 Date: 17-03-2025
Output:
59
VU22CSEN0100800 WEEK-8 Date: 17-03-2025
60
VU22CSEN0100800 WEEK-9 Date: 20-03-2025
Task-9
Date: 20-03-2025
Question: Write a program to understand Propositional logic using
KANREN, SYMPY, pyDatalog packages in Python.
Aim: The aim is to implement and explore Propositional Logic using the Python
libraries KANREN, SYMPY, and pyDatalog. The program will demonstrate how to
represent and solve logical expressions, such as logical propositions, using these
libraries. It will also provide an understanding of how these libraries support logical
reasoning and constraint satisfaction problems.
Description: This program explores Propositional Logic using three different Python
libraries: KANREN, SYMPY, and pyDatalog, each offering unique approaches for
logical reasoning and constraint satisfaction. KANREN is a logic programming library
that allows the representation of logical relationships through relational programming,
enabling the definition of logical variables and querying of satisfiable conditions.
SYMPY, a symbolic mathematics library, provides tools to represent and manipulate
logical expressions symbolically, allowing for simplification and evaluation of
propositional logic formulas. pyDatalog extends the concept of logic programming by
allowing logical rules and queries to be expressed and evaluated using Datalog, a
declarative query language.
Code:
from kanren import run, var, fact, Relation
from sympy import symbols, Or, And, Not, Implies, Equivalent
from pyDatalog import pyDatalog
# ===================== Using Kanren =====================
parent = Relation('parent')
wears = Relation('wears')
brother = Relation('brother')
# Facts from the image (John the king wears the crown, John has a brother)
fact(wears, 'John', 'crown')
fact(brother, 'John', 'L')
x = var()
print("Using kanren:")
61
VU22CSEN0100800 WEEK-9 Date: 20-03-2025
62
VU22CSEN0100800 WEEK-9 Date: 20-03-2025
Output:
63
VU22CSEN0100800 WEEK-10 Date: 20-03-2025
Task -10
# Facts from the image (John the king wears the crown)
64
VU22CSEN0100800 WEEK-10 Date: 20-03-2025
fact(king, 'John')
fact(wears, 'John', 'crown')
fact(rule, 'John')
x = var()
print("Using kanren (Inferential Logic):")
print("Who wears the crown?", run(1, x, wears(x, 'crown')))
print("Who is the king?", run(1, x, king(x)))
print("Who rules the kingdom?", run(1, x, rule(x)))
print("\nUsing sympy:")
print("Expression 1 (A -> B):", expr1)
print("Expression 2 (A <-> NOT C):", expr2)
print("Expression 3 (A AND (B OR NOT C)):", expr3)
Hostile = symbols('Hostile')
Criminal = symbols('Criminal')
West = symbols('West')
Nono = symbols('Nono')
print("\nUsing pyDatalog:")
print("Who is the king?", king[X] == True)
print("Who wears the crown?", wears[X] == 'crown')
print("Who rules?", ruler[X] == True)
66
VU22CSEN0100800 WEEK-10 Date: 20-03-2025
Output:
67
VU22CSEN0100800 WEEK-11 Date: 27-03-2025
Task-11
68
VU22CSEN0100800 WEEK-11 Date: 27-03-2025
Code:
# Import necessary libraries
import pandas as pd
# Dataset
data = {
'Team': ['Red Bull', 'Mercedes', 'Ferrari', 'McLaren', 'Ferrari', 'Mercedes', 'Aston Martin'],
# Create DataFrame
df = pd.DataFrame(data)
label_encoder = LabelEncoder()
df[col] = label_encoder.fit_transform(df[col])
y = df['Outcome']
model.fit(X, y)
plt.figure(figsize=(14, 10))
tree.plot_tree(
model,
69
VU22CSEN0100800 WEEK-11 Date: 27-03-2025
class_names=['Loss', 'Win'],
filled=True,
rounded=True,
fontsize=10,
impurity=True,
node_ids=True,
proportion=False,
ax = plt.gca()
if "Loss" in node.get_text():
node.set_color('red')
node.set_color('blue')
plt.tight_layout()
plt.show()
Output:
The end
70