AI Practical Journal
AI Practical Journal
: 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
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
jug1_capacity = 4
jug2_capacity = 3
target = 2
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
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:
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
Output:
Name: Suraj Vishwakarma Roll No.: 22096
Class: TYBSc IT Subject Artificial Intelligence
Sem: V
initial_state = (1, 2, 3, 4, 5, 6, 0, 7, 8)
target_state = (1, 2, 3, 4, 5, 6, 7, 8, 0)
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
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
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
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
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 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
Output:
Name: Suraj Vishwakarma Roll No.: 22096
Class: TYBSc IT Subject Artificial Intelligence
Sem: V
def is_safe(board,row,col):
for i in range(col):
if board[row][i]:
return False
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)
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': 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
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} 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
A = True # It is raining.
B = False # The ground is not wet.
evaluate_logic(A, B)
Output: