Ai Ass 1
Ai Ass 1
Artificial Intelligence
Question 01:
Simple Agent Creation
Objective: Create a simple agent that can perform actions in a predefined environment.
• Define the Environment: Create a grid-based environment where the agent can move.
• Implement the Agent: Create an agent that can move up, down, left, or right.
• Display the Environment: Write a function to display the current state of the environment and the
agent's position.
• Move the Agent: Implement a method to move the agent based on user input.
Code:
• Python program:
Instructor Name: Dr. Shahnawaz Qureshi Department: AI- Blue
Student Name: Haider Ali Assignment: 01
class GridEnvironment:
def __init__(self, size):
self.size = size self.agent_pos = [0, 0]
# Starting position at top-left
env = GridEnvironment(5)
while True:
env.display() move = input("Enter move (up/down/left/right) or
(shutdown) to shutdown: ").lower() if move in ["up", "down", "left",
"right"]:
env.move(move)
elif move=="shutdown":
print("Shutting down...")
break else:
print("Invalid move, try again.")
Registration No : B23F0001AI054
This GridEnvironment class represents a 5x5 grid where an agent (A) moves based on user input. The agent
starts at the top-left corner (0,0) and can move up, down, left, or right within the grid's boundaries. The
Page|2
Instructor Name: Dr. Shahnawaz Qureshi Department: AI- Blue
Student Name: Haider Ali Assignment: 01
environment updates and displays the agent's position after each move. The program runs in a loop, accepting
movement commands until the user enters "shutdown" to exit.
Registration No : B23F0001AI054
Question 02:
Page|3
Instructor Name: Dr. Shahnawaz Qureshi Department: AI- Blue
Student Name: Haider Ali Assignment: 01
Simple Reflex Agent
• Define an agent that reacts to dirt in an environment.
• Simulate an environment with randomly placed dirt.
• Make the agent clean the environment.
Code:
Python program
import random
class CleaningEnvironment:
def __init__(self, size):
self.size = size
self.agent_pos = [0, 0]
self.grid = [[random.choice(["D", "."]) for _ in range(size)] for _ in
range(size)]
def display(self):
for i in range(self.size):
for j in range(self.size):
if [i, j] == self.agent_pos:
print("A", end=" ")
else:
print(self.grid[i][j], end=" ")
print()
print()
def clean(self):
x, y = self.agent_pos
if self.grid[x][y] == "D":
self.grid[x][y] = "."
print(f"Cleaned at ({x}, {y})!")
Page|4
Instructor Name: Dr. Shahnawaz Qureshi Department: AI- Blue
Student Name: Haider Ali Assignment: 01
This CleaningEnvironment class simulates a simple vacuum cleaner agent in a 3x3 grid.
The grid randomly contains dirty spots ("D") and clean spots ("."). The agent:
1. Starts at (0,0).
2. Moves through every cell in the grid, row by row.
3. Cleans any dirty spot ("D") it encounters.
4. Displays the grid at each step.
Page|5
Instructor Name: Dr. Shahnawaz Qureshi Department: AI- Blue
Student Name: Haider Ali Assignment: 01
Registration No : B23F0001AI054
Question 03:
Model-Based Agent
•Modify the previous agent to store a history of cleaned positions.
•Ensure it does not clean the same position twice unnecessarily.
•Keep track of the environment's current state and update accordingly.
Code:
•Python program:
Page|6
Instructor Name: Dr. Shahnawaz Qureshi Department: AI- Blue
Student Name: Haider Ali Assignment: 01
import random
class
CleaningEnvironment:
def __init__(self, size):
self.size = size
self.agent_pos = [0, 0]
self.grid = [[random.choice(["D", "."]) for _ in range(size)] for _ in range(size)]
self.cleaned_positions = set()
env = CleaningEnvironment(3)
env.move()
Registration No : B23F0001AI054
Registration No : B23F0001AI054
Page|8
Instructor Name: Dr. Shahnawaz Qureshi Department: AI- Blue
Student Name: Haider Ali Assignment: 01
Question 04:
Utility-Based Agent
•Define an agent that maximizes cleaning efficiency.
•Introduce a cost for movement and cleaning.
import random
class
CleaningEnvironment:
def __init__(self, size):
self.size = size
self.agent_pos = [0, 0]
self.grid = [[random.choice(["D", "."]) for _ in range(size)] for _ in
range(size)] self.cleaned_positions = set()
self.utility = 0
Page|9
Instructor Name: Dr. Shahnawaz Qureshi Department: AI- Blue
Student Name: Haider Ali Assignment: 01
self.moves = 0
def display(self):
for i in range(self.size):
for j in range(self.size):
Registration No : B23F0001AI054
if [i, j] ==
self.agent_pos:
print("A", end=" ")
else:
print(self.grid[i][j], end=" ")
print()
print(f"Utility: {self.utility}\n")
def find_nearest_dirt(self):
min_distance = float("inf")
nearest_dirt = None
x, y = self.agent_pos
return nearest_dirt
def move(self):
while True:
self.display() dirt_pos =
self.find_nearest_dirt() if dirt_pos is None:
print("All dirt cleaned! Final Utility:", self.utility)
break
self.agent_pos = list(dirt_pos)
self.moves += 1
self.utility -= 1 print(f"Moving to
{dirt_pos} (-1 Utility)")
self.clean()
env = CleaningEnvironment(5)
env.move()
Registration No : B23F0001AI054
Registration No : B23F0001AI054
P a g e | 11
Instructor Name: Dr. Shahnawaz Qureshi Department: AI- Blue
Student Name: Haider Ali Assignment: 01
Question 04:
Learning Agent
•Implement an agent that learns from past experiences.
•Store previously cleaned positions and avoid redundant cleaning. • Improve
efficiency over multiple runsCode:
•Python program:
import random
P a g e | 12
Instructor Name: Dr. Shahnawaz Qureshi Department: AI- Blue
Student Name: Haider Ali Assignment: 01
class CleaningEnvironment:
P a g e | 13
Instructor Name: Dr. Shahnawaz Qureshi Department: AI- Blue
Student Name: Haider Ali Assignment: 01
Registration No : B23F0001AI054
P a g e | 14
Instructor Name: Dr. Shahnawaz Qureshi Department: AI- Blue
Student Name: Haider Ali Assignment: 01
def __init__(self, size):
self.size = size
self.agent_pos = [0, 0]
self.total_utility = 0
self.total_moves = 0
def reset_environment(self):
"""Resets the grid and tracking data for a fresh round."""
self.grid = [[random.choice(["D", "."]) for _ in range(self.size)] for _ in range(self.size)]
self.cleaned_positions = set()
self.known_dirty_spots = {(i, j) for i in range(self.size) for j in range(self.size) if
self.grid[i][j] == "D"} self.utility = 0 self.moves = 0
self.agent_pos = [0, 0]
def display(self):
"""Displays the grid and agent
position.""" for i in range(self.size):
for j in range(self.size): if [i, j]
== self.agent_pos:
print("A", end=" ") else:
print(self.grid[i][j], end=" ")
print()
print(f"Utility: {self.utility}, Moves: {self.moves}\n")
def clean(self):
"""Cleans dirt at the agent's
position.""" x, y = self.agent_pos
if self.grid[x][y] == "D":
self.grid[x][y] = "."
self.cleaned_positions.add((x, y))
self.known_dirty_spots.discard((x, y))
self.utility += 10
print(f"Cleaned at ({x}, {y})! (+10 Utility)")
def find_nearest_dirt(self):
"""Finds the closest dirt location using Manhattan
distance.""" min_distance = float("inf")
nearest_dirt = None x, y = self.agent_pos
for i, j in
self.known_dirty_spots:
distance = abs(i - x) + abs(j - y)
if distance < min_distance:
min_distance = distance
nearest_dirt = (i, j)
return nearest_dirt
def move(self):
"""Moves the agent towards the nearest dirt until all are
cleaned.""" while self.known_dirty_spots:
self.display() dirt_pos = self.find_nearest_dirt()
if dirt_pos is None: print("All dirt cleaned! Final
Utility:", self.utility) break
self.agent_pos = list(dirt_pos)
self.moves += 1
P a g e | 15
Instructor Name: Dr. Shahnawaz Qureshi Department: AI- Blue
Student Name: Haider Ali Assignment: 01
Registration No : B23F0001AI054
self.utility -= 1
print(f"Moving to {dirt_pos} (-1 Utility)")
self.clean()
P a g e | 16
Instructor Name: Dr. Shahnawaz Qureshi Department: AI- Blue
Student Name: Haider Ali Assignment: 01
Registration No : B23F0001AI054
P a g e | 17
Instructor Name: Dr. Shahnawaz Qureshi Department: AI- Blue
Student Name: Haider Ali Assignment: 01
P a g e | 18
Instructor Name: Dr. Shahnawaz Qureshi Department: AI- Blue
Student Name: Haider Ali Assignment: 01
Registration No : B23F0001AI054
Registration No : B23F0001AI054
P a g e | 19
Instructor Name: Dr. Shahnawaz Qureshi Department: AI- Blue
Student Name: Haider Ali Assignment: 01
P a g e | 20
Instructor Name: Dr. Shahnawaz Qureshi Department: AI- Blue
Student Name: Haider Ali Assignment: 01
Registration No : B23F0001AI054
P a g e | 21