AI_Lab_Manual[1]
AI_Lab_Manual[1]
Prolog (Programming in Logic) is a logic programming language used for tasks involving
symbolic reasoning and non-numerical computation. It is particularly suited for artificial
intelligence applications such as expert systems, natural language processing, and rule-based
reasoning.
Facts in Prolog
Definition:
Facts are simple statements that describe relationships between entities or properties of
an entity. Facts are always true.
parent(john, mary).
parent(mary, susan).
parent(mary, tom).
parent(jane, mary).
Meaning:
parent(john, mary): John is a parent of Mary.
parent(mary, susan): Mary is a parent of Susan.
parent(mary, tom): Mary is a parent of Tom.
parent(jane, mary): Jane is a parent of Mary.
Rules in Prolog
Definition:
Rules define new relationships or properties based on existing facts and other rules.
Rules typically have the form:
head :- body.
This means "the head is true if the body is true." The body can consist of multiple
conditions connected by logical operators like , (and).
Rule 1: Grandparent
grandparent(X, Y) :- parent(X, Z), parent(Z, Y).
Rule 2: Sibling
?- sibling(susan, tom).
Execution:
Prolog checks:
Does susan and tom have a common parent? (Find Z = mary.)
Are susan and tom different? (True.)
Output:
true.
Rule 3: Ancestor
?- ancestor(john, tom).
Execution:
Prolog checks:
Case 1: Is john a parent of tom? (No.)
Case 2: Is john a parent of Z and Z an ancestor of tom?
Find Z = mary.
Check if mary is an ancestor of tom. (True: mary is a parent of tom.)
Output:
true.
Queries in Prolog
Queries are questions asked to the Prolog system. Prolog attempts to resolve these
queries by matching them with facts or deducing answers using rules.
Example Queries:
Who are Mary’s children?
?- parent(mary, X).
?- ancestor(X, tom).
Prolog resolves queries by matching them with facts or the head of rules.
If the head matches, Prolog checks if the body of the rule holds true.
Backtracking:
When a query fails, Prolog backtracks to try alternative solutions. This ensures all
possible answers are explored.
Logical Deduction:
Advantages of Prolog
3. Write predicates One converts centigrade temperatures to Fahrenheit, the other checks
if a temperature is below freezing.
?- centigrade_to_fahrenheit(25, F).
Output:
F = 77.0.
Check if −5∘C is below freezing:
?- below_freezing(-5).
Output:
true.
Check if 10∘C is below freezing:
?- below_freezing(10).
Output:
false.
Find the Fahrenheit equivalent of −10∘C:
?- centigrade_to_fahrenheit(-10, F).
Output:
F = 14.0.
# Initialize BFS
visited = set()
queue = deque([(0, 0)]) # Starting with both jugs empty
path = [ ] # To store the steps taken
while queue:
# Get the current state
jug1, jug2 = queue.popleft()
# Mark as visited
visited.add((jug1, jug2))
path.append((jug1, jug2))
# Possible operations
next_states = [
(jug1_capacity, jug2), # Fill jug1
(jug1, jug2_capacity), # Fill jug2
(0, jug2), # Empty jug1
(jug1, 0), # Empty jug2
(min(jug1 + jug2, jug1_capacity), max(0, jug2 - (jug1_capacity - jug1))), # Pour
jug2 -> jug1
(max(0, jug1 - (jug2_capacity - jug2)), min(jug1 + jug2, jug2_capacity)) # Pour
jug1 -> jug2
]
# Example usage
jug1_capacity = 4
jug2_capacity = 3
target = 2
def move_monkey(self):
if self.state['monkey'] == 'ground':
print("Monkey moves to the box.")
self.state['monkey'] = 'box'
elif self.state['monkey'] == 'box':
print("Monkey climbs up to reach the bananas.")
self.state['monkey'] = 'above_bananas'
def move_box(self):
if self.state['box'] == 'ground':
print("Monkey pushes the box under the bananas.")
self.state['box'] = 'under_bananas'
def solve(self):
print("Initial State:", self.state)
def print_solution(board):
print("\n")
for i in range(col):
if board[row][i] == 'Q':
return False
if board[i][j] == 'Q':
return False
if board[i][j] == 'Q':
return False
return True
print_solution(board)
return True
# Consider this column and try placing this queen in all rows one by one
for i in range(len(board)):
if is_safe(board, i, col):
board[i][col] = 'Q'
return True
return False
def solve_n_queens(n):
return False
return True
solve_n_queens(8)
class Graph:
def __init__(self):
if u not in self.graph:
import heapq
class Node:
self.name = name
class Graph:
def __init__(self):
if u not in self.edges:
self.edges[u] = []
self.edges[u].append((v, cost))
def best_first_search(self, start, goal, heuristic):
heapq.heappush(open_set, start_node)
while open_set:
current_node = heapq.heappop(open_set)
if current_node.name == goal:
return
closed_set.add(current_node.name)
# Explore neighbors
if neighbor in closed_set:
heapq.heappush(open_set, neighbor_node)
# Example usage
if __name__ == "__main__":
# Create a graph
graph = Graph()
graph.add_edge('A', 'B', 1)
graph.add_edge('A', 'C', 4)
graph.add_edge('B', 'D', 2)
graph.add_edge('C', 'D', 5)
graph.add_edge('B', 'E', 3)
graph.add_edge('E', 'D', 1)
heuristic = {
'A': 7,
'B': 6,
'C': 2,
'D': 0,
'E': 1
}
# Perform Best First Search
import heapq
class PuzzleState:
self.board = board
self.size = len(board)
self.goal = self.create_goal_state()
self.heuristic = self.calculate_heuristic()
def create_goal_state(self):
goal = []
for i in range(self.size):
row = []
for j in range(self.size):
else:
row.append(i * self.size + j + 1)
goal.append(row)
return goal
def calculate_heuristic(self):
distance = 0
for i in range(self.size):
for j in range(self.size):
target = self.board[i][j] - 1
return distance
def get_neighbors(self):
neighbors = []
directions = [(-1, 0), (1, 0), (0, -1), (0, 1)] # Up, Down, Left, Right
return neighbors
def __lt__(self, other):
def a_star_search(initial_board):
open_set = []
heapq.heappush(open_set, initial_state)
closed_set = set()
while open_set:
current_state = heapq.heappop(open_set)
if current_state.board == current_state.goal:
return
heapq.heappush(open_set, neighbor_state)
# Example usage
if __name__ == "__main__":
initial_board = [
[1, 2, 3],
[4, 0, 5],
[7, 8, 6]
a_star_search(initial_board)
class TicTacToe:
def __init__(self):
self.board = [' ' for _ in range(9)] # A list to hold the board state
def display_board(self):
print("--+---+--")
print()
self.board[position] = self.current_player
return True
return False
def check_winner(self):
win_conditions = [
return self.board[condition[0]]
return None
def is_draw(self):
def play_game(self):
while True:
self.display_board()
try:
continue
if not self.make_move(move):
continue
except ValueError:
continue
winner = self.check_winner()
if winner:
self.display_board()
break
if self.is_draw():
self.display_board()
print("It's a draw!")
break
self.switch_player()
if __name__ == "__main__":
game = TicTacToe()
game.play_game()
11. Write a Program to find the solution for travelling salesman Problem.
import itertools
"""Calculate the total distance of the given route based on the distance matrix."""
total_distance = 0
for i in range(len(route)):
return total_distance
def traveling_salesman(distance_matrix):
n = len(distance_matrix)
min_distance = float('inf')
best_route = None
# Generate all possible routes (permutations of cities)
min_distance = current_distance
best_route = route
if __name__ == "__main__":
distance_matrix = [
import random
def function(x):
current_position = start
current_value = function(current_position)
for _ in range(max_iterations):
if neighbor_values:
best_neighbor_value = max(neighbor_values)
best_neighbor_position = neighbors[neighbor_values.index(best_neighbor_value)]
# If the best neighbor is better than the current position, move to that neighbor
current_position = best_neighbor_position
current_value = best_neighbor_value
else:
else:
if __name__ == "__main__":
import heapq
class Node:
open_list = []
closed_list = set()
start_node = Node(start)
goal_node = Node(goal)
heapq.heappush(open_list, start_node)
while open_list:
current_node = heapq.heappop(open_list)
closed_list.add(current_node.position)
if current_node.position == goal_node.position:
path = []
while current_node:
path.append(current_node.position)
current_node = current_node.parent
neighbors = [(0, 1), (1, 0), (0, -1), (-1, 0)] # Right, Down, Left, Up
continue
# Check if walkable
if grid[node_position[0]][node_position[1]] != 0:
continue
if child_node.position in closed_list:
continue
# Calculate costs
child_node.g = current_node.g + 1
continue
if __name__ == "__main__":
grid = [
[0, 0, 0, 0, 1, 0],
[0, 1, 0, 1, 0, 0],
[0, 1, 0, 0, 0, 1],
[0, 0, 0, 1, 0, 0],
[1, 0, 0, 0, 1, 0],
[0, 0, 1, 0, 0, 0]
if path:
else:
return
tower_of_hanoi(n - 1, source, auxiliary, target) # Move n-1 disks from source to auxiliary
print(f"Move disk {n} from {source} to {target}") # Move the nth disk from source to target
tower_of_hanoi(n - 1, auxiliary, target, source) # Move n-1 disks from auxiliary to target
if __name__ == "__main__":
num_disks = 3 # You can change this value to test with different numbers of disks
def print_solution(board):
print(" ".join(row))
print()
for i in range(col):
if board[row][i] == 'Q':
return False
return False
if board[i][j] == 'Q':
return False
return True
if col >= N:
print_solution(board)
return True
res = False
for i in range(N):
def solve_n_queens(N):
if __name__ == "__main__":
N = 4 # You can change this value to test with different sizes of the board
solve_n_queens(N)