0% found this document useful (0 votes)
12 views37 pages

AI Practical Journal

The document outlines various practical implementations related to Artificial Intelligence, including algorithms for breadth-first search, depth-first search, and solving problems like the Tower of Hanoi, water jug, and tic-tac-toe using the minimax algorithm. It also covers constraint satisfaction problems and properties of arithmetic operations. Each section includes code snippets and aims to demonstrate the application of AI concepts through programming.

Uploaded by

rowdysuraj1234
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)
12 views37 pages

AI Practical Journal

The document outlines various practical implementations related to Artificial Intelligence, including algorithms for breadth-first search, depth-first search, and solving problems like the Tower of Hanoi, water jug, and tic-tac-toe using the minimax algorithm. It also covers constraint satisfaction problems and properties of arithmetic operations. Each section includes code snippets and aims to demonstrate the application of AI concepts through programming.

Uploaded by

rowdysuraj1234
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/ 37

Name: Suraj Vishwakarma Roll No.

: 22096
Class: TYBSc IT Subject Artificial Intelligence
Sem: V

Practical 1
a) Aim: Implement breadth first search algorithm.
Code:
from collections import deque
def bfs(graph,start):
visited = set()
queue = deque([start])
visited.add(start)
while queue:
vertex = queue.popleft()
print(vertex, end=" ")
for neighbor in graph[vertex]:
if neighbor not in visited:
queue.append(neighbor)
visited.add(neighbor)
if __name__ == "__main__":
graph={
'A':['B','C'],
'B':['A','D','E'],
'C':['A','F'],
'D':['B'],
'E':['B','F'],
'F':['C','E']
}
print("BFS starting from vertex 'A':")
bfs(graph,'A')
Name: Suraj Vishwakarma Roll No.: 22096
Class: TYBSc IT Subject Artificial Intelligence
Sem: V

Output:
Name: Suraj Vishwakarma Roll No.: 22096
Class: TYBSc IT Subject Artificial Intelligence
Sem: V

b) Aim: Implement depth first search algorithm.


Code:
def dfs(graph,start,visited=None):
if visited is None:
visited = set()
visited.add(start)
print(start,end=" ")
for neighbor in graph[start]:
if neighbor not in visited:
dfs(graph,neighbor,visited)
if __name__ == "__main__":
graph = {
'A':['B','C'],
'B':['A','D','E'],
'C':['A','F','G'],
'D':['B','H'],
'E':['B'],
'F':['C','I'],
'G':['C'],
'H':['D'],
'I':['F']
}

print("DFS starting from vertex 'A':")


dfs(graph,'A')

Output:
Name: Suraj Vishwakarma Roll No.: 22096
Class: TYBSc IT Subject Artificial Intelligence
Sem: V

Practical 2
a) Aim: Solve tower of hanoi problem.
Code:
def tower_of_hanoi(n,source,target,auxiliary):
if n == 1:
print(f"Move disk 1 from {source} to {target}")
return
tower_of_hanoi(n-1,source,auxiliary,target)
print(f"Move disk {n} from {source} to {target}")
tower_of_hanoi(n-1,auxiliary,target,source)

if __name__ == "__main__":
n=3
tower_of_hanoi(n,'A','C','B')

Output:
Name: Suraj Vishwakarma Roll No.: 22096
Class: TYBSc IT Subject Artificial Intelligence
Sem: V

b) Aim: Solve water jug problem.


Code:
from collections import deque
def water_jug_problem(capacity_jug1, capacity_jug2, target_volume):
queue = deque()
visited = set()
initial_state = (0, 0)
queue.append((initial_state, []))
visited.add(initial_state)
while queue:
current_state, path = queue.popleft()
jug1, jug2 = current_state
if jug1 == target_volume or jug2 == target_volume:
return path + [current_state]
next_states = [
(capacity_jug1, jug2),
(jug1, capacity_jug2),
(0, jug2),
(jug1, 0),
(jug1 - min(jug1, capacity_jug2 - jug2), jug2 + min(jug1, capacity_jug2 - jug2)),
(jug1 + min(jug2, capacity_jug1 - jug1), jug2 - min(jug2, capacity_jug1 - jug1))
]
for state in next_states:
if state not in visited:
visited.add(state)
queue.append((state, path + [current_state]))
return None

jug1_capacity = 4
jug2_capacity = 3
target = 2

solution = water_jug_problem(jug1_capacity, jug2_capacity, target)

if solution:
print(f"Solution found: {solution}")
Name: Suraj Vishwakarma Roll No.: 22096
Class: TYBSc IT Subject Artificial Intelligence
Sem: V

else:
print("No solution found.")

Output:
Name: Suraj Vishwakarma Roll No.: 22096
Class: TYBSc IT Subject Artificial Intelligence
Sem: V

c) Aim: Shuffle deck of cards.


Code:
import itertools
import random
carddeck = list(itertools.product(range(1,14),["Spade", "Club", "Diamond","Heart"]))
def card(n):
for i in range(n):
carddeck = list(itertools.product(range(1,14),["Spade", "Club", "Diamond", "Heart"]))
random.shuffle(carddeck)
print(carddeck[i][0],carddeck[i][1])
carddeck.remove(carddeck[i])

card(4)
print("\nPress 1 to shuffle cards")
print("Press 2 to exit\n")
choice = int(input("Enter a choice:"))
if(choice == 1):
print("Shuffled Cards:")
card(4)
elif(choice == 2):
print("Exited")
else:
print("Invalid Choice")
Name: Suraj Vishwakarma Roll No.: 22096
Class: TYBSc IT Subject Artificial Intelligence
Sem: V

Output:
Name: Suraj Vishwakarma Roll No.: 22096
Class: TYBSc IT Subject Artificial Intelligence
Sem: V

Practical 3
Aim: Simulate tic - tac - toe game using min-max algorithm.
Code:
import math
import random

BOARD_SIZE = 3
EMPTY = ' '
PLAYER_X = 'X'
PLAYER_O = 'O'

def print_board(board):
for row in board:
print('|'.join(row))
print('-'*(BOARD_SIZE*4-1))

def check_winner(board,player):
for row in range(BOARD_SIZE):
if all(board[row][col]==player for col in range(BOARD_SIZE)):
return True
for col in range(BOARD_SIZE):
if all(board[row][col]==player for row in range(BOARD_SIZE)):
return True
if all(board[i][i]==player for i in range(BOARD_SIZE)):
return True
if all(board[i][BOARD_SIZE-i-1]==player for i in range(BOARD_SIZE)):
return True
return False

def get_empty_positions(board):
return [(r,c) for r in range(BOARD_SIZE) for c in range(BOARD_SIZE) if board[r][c]==EMPTY]

def minimax(board,depth,is_maximizing):
if check_winner(board,PLAYER_X):
return -10+depth
Name: Suraj Vishwakarma Roll No.: 22096
Class: TYBSc IT Subject Artificial Intelligence
Sem: V

if check_winner(board,PLAYER_O):
return 10-depth
if not get_empty_positions(board):
return 0
if is_maximizing:
best_score = -math.inf
for(r,c) in get_empty_positions(board):
board[r][c] = PLAYER_O
score = minimax(board,depth + 1,False)
board[r][c] = EMPTY
best_score = max(score,best_score)
return best_score
else:
best_score = math.inf
for(r,c) in get_empty_positions(board):
board[r][c] = PLAYER_X
score = minimax(board,depth+1,True)
board[r][c] = EMPTY
best_score = min(score,best_score)
return best_score

def best_move(board):
best_score = -math.inf
move = None
for(r,c) in get_empty_positions(board):
board[r][c] = PLAYER_O
score = minimax(board,0,False)
board[r][c] = EMPTY
if score>best_score:
best_score = score
move = (r,c)
return move

def player_move(board):
while True:
try:
r,c = map(int,input("Enter your move (row and column): ").split())
Name: Suraj Vishwakarma Roll No.: 22096
Class: TYBSc IT Subject Artificial Intelligence
Sem: V

if board[r][c]==EMPTY:
board[r][c] = PLAYER_X
break
else:
print("Invalid move! Cell is already occupied.")
except(ValueError,IndexError):
print("Invalid input! Please enter row and column as two integers from 0 to 2.")

def play_game():
board = [[EMPTY]*BOARD_SIZE for _ in range(BOARD_SIZE)]
print("Tic-Tac-Toe Game Started!")
print_board(board)

while True:
player_move(board)
print_board(board)
if check_winner(board,PLAYER_X):
print("Congratulations! You win!")
break
if not get_empty_positions(board):
print("It's a tie!")
break
print("AI is making a move...")
move = best_move(board)
if move:
board[move[0]][move[1]] = PLAYER_O
print_board(board)
if check_winner(board,PLAYER_O):
print("AI wins!")
break
if not get_empty_positions(board):
print("It's a tie!")
break
if __name__ == "__main__":
play_game()
Name: Suraj Vishwakarma Roll No.: 22096
Class: TYBSc IT Subject Artificial Intelligence
Sem: V

Output:
Name: Suraj Vishwakarma Roll No.: 22096
Class: TYBSc IT Subject Artificial Intelligence
Sem: V

Practical 4
a) Aim: Solve constraint satisfaction problem.
Code:

from collections import deque, defaultdict


def find_word_ladder(start_word,end_word,word_list):
word_set = set(word_list)
if end_word not in word_set:
return None
queue = deque([(start_word,[start_word])])
visited = set([start_word])
word_len = len(start_word)
word_dict = defaultdict(list)
for word in word_list:
for i in range(word_len):
word_dict[word[:i] + '*' + word[i + 1:]].append(word)
while queue:
current_word,ladder = queue.popleft()
for i in range(word_len):
intermediate_word = current_word[:i] + '*' + current_word[i + 1:]
for word in word_dict[intermediate_word]:
if word == end_word:
return ladder + [end_word]
if word not in visited:
visited.add(word)
queue.append((word,ladder + [word]))
word_dict[intermediate_word] = []
return None

word_list = ["hot","dot","dog","lot","log","cog"]
start_word = "hit"
end_word = "cog"
result = find_word_ladder(start_word,end_word,word_list)
if result:
print("Shortest word ladder:")
Name: Suraj Vishwakarma Roll No.: 22096
Class: TYBSc IT Subject Artificial Intelligence
Sem: V

for word in result:


print(word)
else:
print("No transformation sequence found.")

Output:
Name: Suraj Vishwakarma Roll No.: 22096
Class: TYBSc IT Subject Artificial Intelligence
Sem: V

b) Aim: Design an application to simulate number puzzle problem.


Code:

from collections import deque


def solve_puzzle(initial_state, target_state):
directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]
def state_to_str(state):
return ''.join(map(str, state))
queue = deque()
visited = set()
queue.append((initial_state, []))
visited.add(state_to_str(initial_state))
while queue:
current_state, path = queue.popleft()
if current_state == target_state:
return path
empty_pos = current_state.index(0)
row, col = empty_pos // 3, empty_pos % 3
for d in directions:
new_row, new_col = row + d[0], col + d[1]
if 0 <= new_row < 3 and 0 <= new_col < 3:
new_state = list(current_state)
new_pos = new_row * 3 + new_col
new_state[empty_pos], new_state[new_pos] = new_state[new_pos], new_state[empty_pos]
new_state_tuple = tuple(new_state)
new_state_str = state_to_str(new_state_tuple)
if new_state_str not in visited:
visited.add(new_state_str)
queue.append((new_state_tuple, path + [new_state]))
return None

initial_state = (1, 2, 3, 4, 5, 6, 0, 7, 8)
target_state = (1, 2, 3, 4, 5, 6, 7, 8, 0)

solution = solve_puzzle(initial_state, target_state)


Name: Suraj Vishwakarma Roll No.: 22096
Class: TYBSc IT Subject Artificial Intelligence
Sem: V

if solution:
print(f"Solution found in {len(solution)} steps:")
for step in solution:
print(step)
else:
print("No solution found.")

Output:
Name: Suraj Vishwakarma Roll No.: 22096
Class: TYBSc IT Subject Artificial Intelligence
Sem: V

Practical 5
a) Aim: Derive the expressions based on Associative Law.
Code:
def associative_addition(a,b,c):
return(a+b)+c,a+(b+c)
def associative_multiplication(a,b,c):
return(a+b)*c, a* (b*c)
a,b,c=2,3,4
result_add = associative_addition(a,b,c)
print(f"Associative property for addition:({a} + {b}) + {c}= {result_add[0]} , {a}+ ({b} + {c})={result_add[1]}")
a,b,c=2,3,4
result_mul=associative_multiplication(a,b,c)
print(f"Associative property for multiplication:({a}*{b})*{c}={result_mul[0]},{a}*({b} * {c}) ={result_mul[1]} ")

Output:
Name: Suraj Vishwakarma Roll No.: 22096
Class: TYBSc IT Subject Artificial Intelligence
Sem: V

b) Aim: Derive the expressions based on Distributive Law.


Code:
def distributive_property(a,b,c):
return a*(b+c),a*b+a*c

a,b,c=2,3,4
result_dist=distributive_property(a,b,c)
print(f"distributive property :{a}*({b}*{c})={result_dist[0]},{a}*{b}+{a}*{c}={result_dist[1]}")

Output:
Name: Suraj Vishwakarma Roll No.: 22096
Class: TYBSc IT Subject Artificial Intelligence
Sem: V

Practical 6

Aim: Implement Missionary Cannibal problem.


Code:
from collections import deque
def is_valid(state):
left_m, left_c, boat, right_m, right_c = state
if left_m < left_c and left_m > 0:
return False
if right_m < right_c and right_m > 0:
return False
return True
def generate_next_states(state):
possible_states = []
left_m, left_c, boat, right_m, right_c = state
if boat == 1:
for m in range(3):
for c in range(3):
if 1 <= m + c <= 2:
new_left_m = left_m - m
new_left_c = left_c - c
new_right_m = right_m + m
new_right_c = right_c + c
if is_valid((new_left_m, new_left_c, 0, new_right_m, new_right_c)):
possible_states.append((new_left_m, new_left_c, 0, new_right_m, new_right_c))
else:
for m in range(3):
for c in range(3):
if 1 <= m + c <= 2:
new_left_m = left_m + m
new_left_c = left_c + c
new_right_m = right_m - m
new_right_c = right_c - c
if is_valid((new_left_m, new_left_c, 1, new_right_m, new_right_c)):
possible_states.append((new_left_m, new_left_c, 1, new_right_m, new_right_c))
Name: Suraj Vishwakarma Roll No.: 22096
Class: TYBSc IT Subject Artificial Intelligence
Sem: V

return possible_states
def solve_missionary_cannibal():
initial_state = (3, 3, 1, 0, 0)
target_state = (0, 0, 0, 3, 3)
if not is_valid(initial_state):
raise ValueError("Initial state is invalid!")

queue = deque()
visited = set()
queue.append(([initial_state], []))
visited.add(initial_state)
while queue:
current_path, actions = queue.popleft()
current_state = current_path[-1]
if current_state == target_state:
return actions
for next_state in generate_next_states(current_state):
if next_state not in visited:
visited.add(next_state)
queue.append((current_path + [next_state], actions + [f"Move {'M'*next_state[0]}C{'C'*next_state[1]}
{'to' if next_state[2] == 1 else 'from'} {'right' if next_state[2] == 1 else 'left'} bank"]))
return None
solution = solve_missionary_cannibal()
if solution:
print("Solution found:")
for action in solution:
print(action)
else:
print("No solution found.")

Output:
Name: Suraj Vishwakarma Roll No.: 22096
Class: TYBSc IT Subject Artificial Intelligence
Sem: V
Name: Suraj Vishwakarma Roll No.: 22096
Class: TYBSc IT Subject Artificial Intelligence
Sem: V

Practical 7
a) Aim: Implement Travelling Salesman Problem
Code:
from sys import maxsize
from itertools import permutations
V=4

def travellingSalesmanProblem(graph, s):


vertex = []
for i in range(V):
if i != s:
vertex.append(i)

min_path = maxsize
next_permutation=permutations(vertex)
for i in next_permutation:
current_pathweight = 0
k=s
for j in i:
current_pathweight += graph[k][j]
k=j
current_pathweight += graph[k][s]
min_path = min(min_path, current_pathweight)
return min_path

if _name_ == "_main_":
graph = [[0, 10, 15, 20], [10, 0, 35, 25],
[15, 35, 0, 30], [20, 25, 30, 0]]
s=0
print(travellingSalesmanProblem(graph, s))
Name: Suraj Vishwakarma Roll No.: 22096
Class: TYBSc IT Subject Artificial Intelligence
Sem: V

Output:
Name: Suraj Vishwakarma Roll No.: 22096
Class: TYBSc IT Subject Artificial Intelligence
Sem: V

b) Aim: Implement hill climbing problem.


Code:
import random
def objective_function(x):
return -(x**2-4*x+4)

def hill_climbing(starting_point,step_size,max_iterations):
current_point = starting_point
current_value = objective_function(current_point)
for _ in range(max_iterations):
next_point = current_point + random.uniform(-step_size,step_size)
next_value = objective_function(next_point)
if next_value > current_value:
current_point = next_point
current_value = next_value
return current_point,current_value

if __name__ == "__main__":
starting_point = random.uniform(-10,10)
step_size = 0.1
max_iterations = 1000
best_point,best_value = hill_climbing(starting_point,step_size,max_iterations)
print(f"Best point: {best_point}")
print(f"Best value: {best_value}")

Output:
Name: Suraj Vishwakarma Roll No.: 22096
Class: TYBSc IT Subject Artificial Intelligence
Sem: V

Practical 8
a) Aim: Implement Heuristics Search
Code:
import heapq
class Node:
def __init__(self, name, parent=None, g=0, h=0):
self.name = name
self.parent = parent
self.g = g
self.h = h
self.f = g + h

def __lt__(self, other):


return self.f < other.f

def a_star_search(start, goal, h_func):


open_set = []
closed_set = set()
start_node = Node(start, None, 0, h_func(start))
heapq.heappush(open_set, start_node)
while open_set:
current_node = heapq.heappop(open_set)
if current_node.name == goal:
return reconstruct_path(current_node)
closed_set.add(current_node.name)
for neighbor, cost in get_neighbors(current_node.name):
if neighbor in closed_set:
continue
g_cost = current_node.g + cost
h_cost = h_func(neighbor)
neighbor_node = Node(neighbor, current_node, g_cost, h_cost)
if any(node.name == neighbor and node.g <= g_cost for node in open_set):
continue
heapq.heappush(open_set, neighbor_node)
return None
Name: Suraj Vishwakarma Roll No.: 22096
Class: TYBSc IT Subject Artificial Intelligence
Sem: V

def reconstruct_path(node):
path = []
while node:
path.append(node.name)
node = node.parent
return path[::-1]

def get_neighbors(node):
graph = {
'A': [('B', 1), ('C', 4)],
'B': [('A', 1), ('C', 2), ('D', 5)],
'C': [('A', 4), ('B', 2), ('D', 1)],
'D': [('B', 5), ('C', 1)]
}
return graph.get(node, [])

def heuristic(node):
heuristics = {
'A': 7,
'B': 6,
'C': 2,
'D': 0
}
return heuristics.get(node, float('inf'))

start_node = 'A'
goal_node = 'D'
path = a_star_search(start_node, goal_node, heuristic)
print("Path from {} to {}: {}".format(start_node, goal_node, path))
Name: Suraj Vishwakarma Roll No.: 22096
Class: TYBSc IT Subject Artificial Intelligence
Sem: V

Output:
Name: Suraj Vishwakarma Roll No.: 22096
Class: TYBSc IT Subject Artificial Intelligence
Sem: V

b) Aim: Implement alpha beta search.


Code:
MAX, MIN = 1000, -1000
def minimax(depth, nodeIndex, maximisingPlayer, values, alpha, beta):
if depth == 3:
return values[nodeIndex]
if maximisingPlayer:
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
if __name__ == "__main__":
values = [3,2,9,1,2,0,-1,2]
print("The optimal value is : ",minimax(0,0,True,values,MIN,MAX))
Name: Suraj Vishwakarma Roll No.: 22096
Class: TYBSc IT Subject Artificial Intelligence
Sem: V

Output:
Name: Suraj Vishwakarma Roll No.: 22096
Class: TYBSc IT Subject Artificial Intelligence
Sem: V

c) Aim: Simulate 4-Queen / N-Queen problem.


Code:
def print_board(board):
for row in board:
print(' '.join(['Q' if cell else '.' for cell in row]))
print()

def is_safe(board,row,col):
for i in range(col):
if board[row][i]:
return False

for i,j in zip(range(row,-1,-1),range(col,-1,-1)):


if board[i][j]:
return False

for i,j in zip(range(row,len(board),1),range(col,-1,-1)):


if board[i][j]:
return False
return True

def solve_n_queens(board,col):
if col >=len(board):
return True
for i in range(len(board)):
if is_safe(board,i,col):
board[i][col] = True
if solve_n_queens(board,col + 1):
return True
board[i][col] = False
return False

def solve_4_queens():
board = [[False for _ in range(4)] for _ in range(4)]
if solve_n_queens(board,0):
print("Solution found: ")
Name: Suraj Vishwakarma Roll No.: 22096
Class: TYBSc IT Subject Artificial Intelligence
Sem: V

print_board(board)
else:
print("No Solution Exists")

if __name__ == "__main__":
solve_4_queens()

Output:
Name: Suraj Vishwakarma Roll No.: 22096
Class: TYBSc IT Subject Artificial Intelligence
Sem: V

Practical 9
a) Aim: Implement A* algorithm.
Code:
import heapq
class Node:
def __init__(self,name,cost=0,heuristic=0):
self.name = name
self.cost = cost
self.heuristic = heuristic
self.parent = None
def __It__(self,other):
return(self.cost + self.heuristic) < (other.cost + other.heuristic)

def a_star(start_name,goal_name,graph,heuristics):
open_list = []
closed_list = set()
start_node = Node(start_name,cost=0,heuristic=heuristics.get(start_name,float('inf')))
heapq.heappush(open_list,(start_node.cost + start_node.heuristic,start_node))
while open_list:
_,current_node = heapq.heappop(open_list)
if current_node.name == goal_name:
path = []
while current_node:
path.append(current_node.name)
current_node = current_node.parent
return path[::-1]
closed_list.add(current_node.name)

for neighbor, cost in graph.get(current_node.name,{}).items():


if neighbor in closed_list:
continue
g_cost = current_node.cost + cost
h_cost = heuristics.get(neighbor,float('inf'))
neighbor_node = Node(neighbor,cost=g_cost,heuristic=h_cost)
neighbor_node.parent = current_node
Name: Suraj Vishwakarma Roll No.: 22096
Class: TYBSc IT Subject Artificial Intelligence
Sem: V

if not any(node.name == neighbor and node.cost <= g_cost for _,node in open_list):
heapq.heappush(open_list,(g_cost + h_cost,neighbor_node))
return None

if __name__ == "__main__":
graph = {
'A':{'B':1, 'C':4},
'B':{'C':2, 'D':5},
'C':{'D':1},
'D':{}
}
heuristics = {
'A':7,
'B':6,
'C':2,
'D':0
}

path = a_star('A','D',graph,heuristics)
print("Path found:",path)

Output:
Name: Suraj Vishwakarma Roll No.: 22096
Class: TYBSc IT Subject Artificial Intelligence
Sem: V

b) Aim: Implement AO* algorithm.


Code:
class AOStarNode:
def __init__(self, name, heuristic=0):
self.name = name
self.heuristic = heuristic
self.children = []
self.parent = None
def ao_star(start_name, goal_name, graph, heuristics):
open_list = [AOStarNode(start_name, heuristics.get(start_name, float('inf')))]
closed_list = set()
while open_list:
current_node = open_list.pop(0)
if current_node.name == goal_name:
path = []
while current_node:
path.append(current_node.name)
current_node = current_node.parent
return path[::-1]
closed_list.add(current_node.name)
for child_name in graph.get(current_node.name, []):
if child_name in closed_list:
continue
child_node = AOStarNode(child_name, heuristics.get(child_name, float('inf')))
child_node.parent = current_node
open_list.append(child_node)
return None
if __name__ == "__main__":
graph = {
'A': ['B', 'C'],
'B': ['D'],
'C': ['D'],
'D': []
}
heuristics = {
'A': 4,
Name: Suraj Vishwakarma Roll No.: 22096
Class: TYBSc IT Subject Artificial Intelligence
Sem: V

'B': 3,
'C': 2,
'D': 0
}
path = ao_star('A', 'D', graph, heuristics)
print("Path found:", path)

Output:
Name: Suraj Vishwakarma Roll No.: 22096
Class: TYBSc IT Subject Artificial Intelligence
Sem: V

Practical 10
Aim: Derive the predicate. (for eg.: Sachin is batsman, batsman is
cricketer) -> Sachin is cricketer
Code:
def implies(A, B):
return (not A) or B

def double_implies(A, B):


return (A and B) or (not A and not B)

def evaluate_logic(A, B):


sentence_A = "It is raining."
sentence_B = "The ground is wet."

and_result = A
or_result = A
not_A_result = A
implies_result = implies(A, B)
double_implies_result = double_implies(A, B)

print(f"{sentence_A} AND {sentence_B}:")


if and_result:
print(f"Both statements are true: 'It is raining' and 'The ground is wet.'\n")
else:
print(f"At least one statement is false: 'It is raining' and 'The ground is wet.'\n")

print(f"{sentence_A} OR {sentence_B}:")
if or_result:
print(f"At least one of the statements is true: 'It is raining' or 'The ground is wet.'\n")
else:
print(f"Both statements are false: 'It is not raining' and 'The ground is not wet.'\n")

print(f"NOT ({sentence_A}):")
if not_A_result:
Name: Suraj Vishwakarma Roll No.: 22096
Class: TYBSc IT Subject Artificial Intelligence
Sem: V

print(f"'It is not raining.'\n")


else:
print(f"'It is raining.'\n")

print(f"({sentence_A}) IMPLIES ({sentence_B}):")


if implies_result:
print(f"If 'It is raining', then 'The ground is wet' is true.\n")
else:
print(f"The statement 'If it is raining, then the ground is wet' is false.\n")

print(f"({sentence_A}) IF AND ONLY IF ({sentence_B}):")


if double_implies_result:
print(f"'It is raining' if and only if 'The ground is wet' (both are either true or false).\n")
else:
print(f"'It is raining' does not correspond to 'The ground is wet' (one is true and the other is false).\n")

A = True # It is raining.
B = False # The ground is not wet.

evaluate_logic(A, B)

Output:

You might also like