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

Index AI

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

List of questions for Practical – Introduction To Artificial Intelligence

s. Detailed Statement Sign

l. Write a program to implement Breadth First and Depth First Search

2. Write a program to implement Water Jug Problem

3. Write a Program A* search algorithm

4. Write a program to implement AO* algorithm

5. Write a program to implement 4-Queen Problem

6. Write a program to implement hill climbing & steepest ascent hill


climbing algorithm
7. Write a program to implement Travelling Salesman Problem

8. (a) Write a program to implement List operations (Nested List,


Length, Concatenation, Membership, Iteration, Indexing and
Slicing)?
(b) Write a program to implement List methods (Add, A end,
and Extend & Delete).
9. Write a program to implement First Order Predicate using:

a. Backward Chaining
b. Forward Chaining
10. Write a program for Text Classification for the given sentence using
NLTK
PRACTICAL 1
Write a program to implement Breadth First and
Depth First Search.
SOURCE CODE
from collections import defaultdict
class Graph:
def __init__(self):
self.graph = defaultdict(list)

def add_edge(self, u, v):


self.graph[u].append(v)
def bfs(self, start):
visited = [False] * len(self.graph)
queue = [start]
visited[start] = True
while queue:
current = queue.pop(0)
print(current, end=" ")
for neighbor in self.graph[current]:
if not visited[neighbor]:
queue.append(neighbor)
visited[neighbor] = True
def dfs_util(self, v, visited):
visited[v] = True
print(v, end=" ")

for neighbor in self.graph[v]:


if not visited[neighbor]:
self.dfs_util(neighbor, visited)

def dfs(self, start):


visited = [False] * len(self.graph)
self.dfs_util(start, visited)
g = Graph()
g.add_edge(0, 1)
g.add_edge(0, 2)
g.add_edge(1, 2)
g.add_edge(2, 0)
g.add_edge(2, 3)
g.add_edge(3, 3)

print("BFS Traversal:")
g.bfs(2)
print("\nDFS Traversal:")
g.dfs(2)

OUTPUT
PRACTICAL 2
Write a program to implement Water Jug Problem.
SOURCE CODE
# Function to find all possible states for pouring water from one jug to
another
def pour(jug1, jug2, capacities):
max1, max2 = capacities
states = []

# Pour from jug1 to jug2


if jug1 > 0 and jug2 < max2:
amount = min(jug1, max2 - jug2)
states.append((jug1 - amount, jug2 + amount))

# Pour from jug2 to jug1


if jug2 > 0 and jug1 < max1:
amount = min(jug2, max1 - jug1)
states.append((jug1 + amount, jug2 - amount))

return states

# Function to solve the Water Jug problem using BFS


def water_jug_bfs(capacities, target):
visited = set()
queue = deque([(0, 0)]) # Initial state

while queue:
current_state = queue.popleft()
if current_state == target:
return True

visited.add(current_state)
jug1, jug2 = current_state

for state in pour(jug1, jug2, capacities):


if state not in visited:
queue.append(state)
return False
# Example usage
capacities = (4, 3) # Capacities of the jugs
target = (2, 0) # Target state (2 gallons in jug 1 and 0 gallons in
jug 2)
if water_jug_bfs(capacities, target):
print("Target state is reachable.")
else:
print("Target state is not reachable.")

OUTPUT
PRACTICAL 3
Write a Program A* search algorithm
SOURCE CODE
import heapq
class Node:
def __init__(self, state, parent=None, action=None, g=0, h=0):
self.state = state
self.parent = parent
self.action = action
self.g = g # cost from start node to current node
self.h = h # heuristic cost from current node to goal node
def f(self):
return self.g + self.h
def astar_search(initial_state, goal_state, heuristic):
open_list = []
closed_list = set()

start_node = Node(initial_state)
start_node.h = heuristic(initial_state, goal_state)

heapq.heappush(open_list, (start_node.f(), id(start_node), start_node))


while open_list:
_, _, current_node = heapq.heappop(open_list)
if current_node.state == goal_state:
path = []
while current_node:
path.append(current_node.state)
current_node = current_node.parent
return path[::-1]
closed_list.add(current_node.state)
for next_state, action, cost in get_successors(current_node.state):
if next_state in closed_list:
continue
g = current_node.g + cost
h = heuristic(next_state, goal_state)
child_node = Node(next_state, current_node, action, g, h)
heapq.heappush(open_list, (child_node.f(), id(child_node),
child_node))
return None
def get_successors(state):
successors = []
return successors
def heuristic(state, goal_state):
return abs(state[0] - goal_state[0]) + abs(state[1] - goal_state[1])
# Example usage
initial_state = (0, 0)
goal_state = (5, 5)
path = astar_search(initial_state, goal_state, heuristic)
print("Path found:", path)

OUTPUT
PRACTICAL 4
Write a program to implement AO* algorithm
SOURCE CODE
# Cost to find the AND and OR path
def Cost(H, condition, weight = 1):
cost = {}
if 'AND' in condition:
AND_nodes = condition['AND']
Path_A = ' AND '.join(AND_nodes)
PathA = sum(H[node]+weight for node in AND_nodes)
cost[Path_A] = PathA

if 'OR' in condition:
OR_nodes = condition['OR']
Path_B =' OR '.join(OR_nodes)
PathB = min(H[node]+weight for node in OR_nodes)
cost[Path_B] = PathB
return cost

# Update the cost


def update_cost(H, Conditions, weight=1):
Main_nodes = list(Conditions.keys())
Main_nodes.reverse()
least_cost= {}
for key in Main_nodes:
condition = Conditions[key]
print(key,':', Conditions[key],'>>>', Cost(H, condition,
weight))
c = Cost(H, condition, weight)
H[key] = min(c.values())
least_cost[key] = Cost(H, condition, weight)
return least_cost

# Print the shortest path


def shortest_path(Start,Updated_cost, H):
Path = Start
if Start in Updated_cost.keys():
Min_cost = min(Updated_cost[Start].values())
key = list(Updated_cost[Start].keys())
values = list(Updated_cost[Start].values())
Index = values.index(Min_cost)

# FIND MINIMIMUM PATH KEY


Next = key[Index].split()
# ADD TO PATH FOR OR PATH
if len(Next) == 1:

Start =Next[0]
Path += '<--' +shortest_path(Start, Updated_cost, H)
# ADD TO PATH FOR AND PATH
else:
Path +='<--('+key[Index]+') '

Start = Next[0]
Path += '[' +shortest_path(Start, Updated_cost, H) + ' +
'

Start = Next[-1]
Path += shortest_path(Start, Updated_cost, H) + ']'

return Path
H = {'A': -1, 'B': 5, 'C': 2, 'D': 4, 'E': 7, 'F': 9, 'G': 3, 'H': 0,
'I':0, 'J':0}

Conditions = {
'A': {'OR': ['B'], 'AND': ['C', 'D']},
'B': {'OR': ['E', 'F']},
'C': {'OR': ['G'], 'AND': ['H', 'I']},
'D': {'OR': ['J']}
}
# weight
weight = 1
# Updated cost
print('Updated Cost :')
Updated_cost = update_cost(H, Conditions, weight=1)
print('*'*75)
print('Shortest Path :\n',shortest_path('A', Updated_cost,H))

OUTPUT
PRACTICAL 5
Write a program to implement 4-Queen Problem
SOURCE CODE
def is_safe(board, row, col):
# Check if there is a queen in the same row to the left
for i in range(col):
if board[row][i] == 1:
return False
# Check upper diagonal on the left side
for i, j in zip(range(row, -1, -1), range(col, -1, -1)):
if board[i][j] == 1:
return False
# Check lower diagonal on the left side
for i, j in zip(range(row, len(board)), range(col, -1, -1)):
if board[i][j] == 1:
return False
return True
def solve_queen_problem(board, col):
# Base case: if all queens are placed
if col >= len(board):
return True
for i in range(len(board)):
if is_safe(board, i, col):
board[i][col] = 1
if solve_queen_problem(board, col + 1):
return True
board[i][col] = 0
return False
def print_solution(board):
for row in board:
print(row)
def four_queen_problem():
# Initialize 4x4 chessboard
board = [[0] * 4 for _ in range(4)]
if not solve_queen_problem(board, 0):
print("Solution does not exist")
return False
print_solution(board)
return True
# Solve and print solution for 4-Queen Problem
four_queen_problem()

OUTPUT
PRACTICAL 6
Write a program to implement hill climbing &
steepest ascent hill climbing algorithm.

SOURCE CODE OF HILL CLIMBING


import random

def hill_climbing(problem, max_iterations):


current_state = problem.initial_state()

for _ in range(max_iterations):
neighbors = problem.neighbors(current_state)
next_state = max(neighbors, key=lambda state:
problem.heuristic(state))

if problem.heuristic(next_state) <= problem.heuristic(current_state):


return current_state
current_state = next_state

return current_state

class Problem:
def initial_state(self):
return random.randint(1, 100)

def neighbors(self, state):


return [state + random.randint(-10, 10) for _ in range(10)]

def heuristic(self, state):


return -abs(state - 50)

# Example usage
problem = Problem()
solution = hill_climbing(problem, 100)
print("Solution found by Hill Climbing:", solution)
print("Heuristic value at solution state:", problem.heuristic(solution))

OUTPUT
SOURCE CODE OF STEEPEST ASCENT HILL CLIMBING
import random

def steepest_ascent_hill_climbing(problem, max_iterations):


current_state = problem.initial_state()

for _ in range(max_iterations):
neighbors = problem.neighbors(current_state)
best_neighbor = max(neighbors, key=lambda state:
problem.heuristic(state))

if problem.heuristic(best_neighbor) <=
problem.heuristic(current_state):
return current_state
current_state = best_neighbor

return current_state

class Problem:
def initial_state(self):
return random.randint(1, 100)

def neighbors(self, state):


return [state + random.randint(-10, 10) for _ in range(10)]

def heuristic(self, state):


return -abs(state - 50)

# Example usage
problem = Problem()
solution = steepest_ascent_hill_climbing(problem, 100)
print("Solution found by Steepest Ascent Hill Climbing:", solution)
print("Heuristic value at solution state:", problem.heuristic(solution))

OUTPUT
PRACTICAL 7
Write a program to implement Travelling Salesman
Problem.
SOURCE CODE
import itertools

def calculate_distance(points):
# Calculate the total distance between points in the given order
total_distance = 0
num_points = len(points)
for i in range(num_points):
total_distance += distance(points[i], points[(i + 1) % num_points])
return total_distance

def distance(point1, point2):


# Euclidean distance between two points
return ((point1[0] - point2[0]) ** 2 + (point1[1] - point2[1]) ** 2) **
0.5

def brute_force_tsp(points):
# Generate all possible permutations of the points
all_permutations = itertools.permutations(points)
min_distance = float('inf')
best_route = None

# Iterate over all permutations and find the one with the minimum
distance
for permutation in all_permutations:
current_distance = calculate_distance(permutation)
if current_distance < min_distance:
min_distance = current_distance
best_route = permutation

return best_route, min_distance

# Example usage
points = [(0, 0), (1, 2), (3, 1), (2, 3)]
best_route, min_distance = brute_force_tsp(points)
print("Best route:", best_route)
print("Minimum distance:", min_distance)

OUTPUT
PRACTICAL 8
(a)Write a program to implement List
operations (Nested List,Length,
Concatenation, Membership, Iteration,
Indexing and Slicing)?
SOURCE CODE
# Nested List
nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

# Length of a List
print("Length of the nested list:", len(nested_list))

# Concatenation of Lists
list1 = [1, 2, 3]
list2 = [4, 5, 6]
concatenated_list = list1 + list2
print("Concatenated list:", concatenated_list)

# Membership Test
print("Is 2 present in list1?", 2 in list1)

# Iteration through a List


print("Elements of list1:")
for item in list1:
print(item)

# Indexing
print("Element at index 1 of list2:", list2[1])

# Slicing
print("Sliced elements from index 1 to 3 of list2:", list2[1:3])

OUTPUT
(b) Write a program to implement List
methods (Add, A end, and Extend &
Delete).
SOURCE CODE
# Nested List
nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

# Length of a List
print("Length of the nested list:", len(nested_list))

# Concatenation of Lists
list1 = [1, 2, 3]
list2 = [4, 5, 6]
concatenated_list = list1 + list2
print("Concatenated list:", concatenated_list)

# Membership Test
print("Is 2 present in list1?", 2 in list1)

# Iteration through a List


print("Elements of list1:")
for item in list1:
print(item)

# Indexing
print("Element at index 1 of list2:", list2[1])

# Slicing
print("Sliced elements from index 1 to 3 of list2:", list2[1:3])

OUTPUT
PRACTICAL 9
(a)Write a program to implement First
Order Predicate using Backward
Chaining .
SOURCE CODE
class Predicate:
def __init__(self, name, arguments):
self.name = name
self.arguments = arguments

def __str__(self):
return f"{self.name}({', '.join(self.arguments)})"

class Rule:
def __init__(self, head, body):
self.head = head
self.body = body

def __str__(self):
return f"{self.head} :- {' ,'.join([str(p) for p in self.body])}"

class KnowledgeBase:
def __init__(self):
self.facts = []
self.rules = []

def add_fact(self, fact):


self.facts.append(fact)

def add_rule(self, rule):


self.rules.append(rule)

def backward_chaining(kb, goal):


if goal in kb.facts:
return True
for rule in kb.rules:
if rule.head.name == goal.name:
body_result = all(backward_chaining(kb, predicate) for
predicate in rule.body)
if body_result:
return True
return False

# Example usage
if __name__ == "__main__":
# Creating a knowledge base
kb = KnowledgeBase()

# Adding facts to the knowledge base


kb.add_fact(Predicate("Parent", ["Adam", "John"]))
kb.add_fact(Predicate("Parent", ["Eve", "John"]))
kb.add_fact(Predicate("Parent", ["John", "Alex"]))
kb.add_fact(Predicate("Parent", ["John", "Bob"]))
# Defining rules
rule1 = Rule(Predicate("Ancestor", ["?x", "?y"]), [Predicate("Parent",
["?x", "?y"])])
rule2 = Rule(Predicate("Ancestor", ["?x", "?z"]), [Predicate("Parent",
["?x", "?y"]), Predicate("Ancestor", ["?y", "?z"])])

# Adding rules to the knowledge base


kb.add_rule(rule1)
kb.add_rule(rule2)

# Goal for backward chaining


goal = Predicate("Ancestor", ["Adam", "Alex"])

# Backward Chaining
if backward_chaining(kb, goal):
print(f"{goal} is true.")
else:
print(f"{goal} is false.")

OUTPUT
(b)Write a program to implement First
Order Predicate using Forward
Chaining .
SOURCE CODE
class Predicate:
def __init__(self, name, arguments):
self.name = name
self.arguments = arguments

def __str__(self):
return f"{self.name}({', '.join(self.arguments)})"

class Rule:
def __init__(self, head, body):
self.head = head
self.body = body

def __str__(self):
return f"{self.head} :- {' ,'.join([str(p) for p in self.body])}"

class KnowledgeBase:
def __init__(self):
self.facts = []
self.rules = []

def add_fact(self, fact):


self.facts.append(fact)

def add_rule(self, rule):


self.rules.append(rule)

def forward_chaining(kb, goal):


inferred = set()
agenda = kb.facts[:]
while agenda:
p = agenda.pop(0)
if p == goal:
return True
if p not in inferred:
inferred.add(p)
for rule in kb.rules:
if p.name == rule.head.name:
agenda.extend(rule.body)
return False

# Example usage
if __name__ == "__main__":
# Creating a knowledge base
kb = KnowledgeBase()

# Adding facts to the knowledge base


kb.add_fact(Predicate("Parent", ["Adam", "John"]))
kb.add_fact(Predicate("Parent", ["Eve", "John"]))
kb.add_fact(Predicate("Parent", ["John", "Alex"]))
kb.add_fact(Predicate("Parent", ["John", "Bob"]))
# Defining rules
rule1 = Rule(Predicate("Ancestor", ["?x", "?y"]), [Predicate("Parent",
["?x", "?y"])])
rule2 = Rule(Predicate("Ancestor", ["?x", "?z"]), [Predicate("Parent",
["?x", "?y"]), Predicate("Ancestor", ["?y", "?z"])])

# Adding rules to the knowledge base


kb.add_rule(rule1)
kb.add_rule(rule2)

# Goal for forward chaining


goal = Predicate("Ancestor", ["Adam", "Alex"])

# Forward Chaining
if forward_chaining(kb, goal):
print(f"{goal} is true.")
else:
print(f"{goal} is false.")

OUTPUT
PRACTICAL 10
Write a program for Text Classification for the given
sentence using NLTK.
SOURCE CODE
import nltk
from nltk.corpus import movie_reviews
from nltk.tokenize import word_tokenize
from nltk.classify import NaiveBayesClassifier
from nltk.classify.util import accuracy

# Download NLTK resources (if not already downloaded)


nltk.download('movie_reviews')
nltk.download('punkt')

# Prepare data
documents = [(list(movie_reviews.words(fileid)), category)
for category in movie_reviews.categories()
for fileid in movie_reviews.fileids(category)]

# Shuffle the documents


import random
random.shuffle(documents)

# Define feature extractor


all_words = nltk.FreqDist(w.lower() for w in movie_reviews.words())
word_features = list(all_words)[:2000] # Select top 2000 words as features

def document_features(document):
document_words = set(document)
features = {}
for word in word_features:
features[word] = (word in document_words)
return features

# Extract features and split data into training and testing sets
featuresets = [(document_features(d), c) for (d,c) in documents]
train_set, test_set = featuresets[100:], featuresets[:100]

# Train the classifier


classifier = NaiveBayesClassifier.train(train_set)

# Test the classifier


print("Accuracy:", accuracy(classifier, test_set))

# Example usage
review = "This movie was great!"
words = word_tokenize(review)
features = document_features(words)
print("Predicted label:", classifier.classify(features))
SOURCE CODE

You might also like