Ai Lab
Ai Lab
SESSION 2023-24
PROJECT FILE
ARITIFICIAL INTELLIGENCE LAB
Prolog and Lisp are two founda onal programming languages that are
widely studied in the fields of ar ficial intelligence (AI), computer science,
and logic programming. Both languages have dis nct paradigms and were
developed for different purposes, but they have influenced the
development of many other languages and concepts in the compu ng
world. Below is an overview of each language and its characteris cs:
Overview:
Developed by: Alain Colmerauer and Philippe Roussel in the early 1970s.
Paradigm: Logic programming language.
Key Feature: Based on formal logic and uses rules and facts to infer
answers.
Primary Use: Knowledge representa on, natural language processing,
expert systems, and AI.
Core Concepts:
1. Facts:
o Represent basic asser ons about the world. For example:
o parent(john, mary).
o parent(mary, susan).
These facts state that John is a parent of Mary and Mary is a parent of
Susan.
2. Rules:
o Define rela onships between facts. For example:
o grandparent(X, Y) :- parent(X, Z), parent(Z, Y).
This rule states that X is a grandparent of Y if X is a parent of Z and Z is a
parent of Y.
3. Queries:
o Used to ask Prolog ques ons. For example:
o ?- grandparent(john, susan).
Prolog tries to find a solu on based on the facts and rules defined.
4. Backtracking:
o Prolog uses backtracking to explore different possible solu ons. If
a solu on is not found, it backtracks to previous decisions to try
alterna ve paths.
5. Unifica on:
o A process of making two terms iden cal by finding a common
subs tu on. For example:
o parent(X, Y).
Prolog would try to unify X and Y with the exis ng facts in the database.
Strengths of Prolog:
Declara ve Language: You describe what you want, not how to achieve
it.
Expressiveness: Ideal for problems involving complex rela onships and
logical reasoning.
Backtracking and pa ern matching allow elegant solu ons to problems
like puzzles, planning, and search.
Overview:
Developed by: John McCarthy in 1958.
Paradigm: Func onal programming language, with symbolic expression
manipula on.
Key Feature: Manipula on of lists and recursive func ons.
Primary Use: AI, symbolic processing, and general-purpose
programming.
Core Concepts:
1. Symbolic Expressions (S-expressions):
o Lisp uses S-expressions to represent both code and data. An S-
expression is a list, typically wri en in parentheses. For example:
o (+ 2 3)
This expression represents the addi on of 2 and 3. The operator (+) and
operands (2 and 3) are all part of a list.
2. Recursive Func ons:
o Lisp relies heavily on recursion as a fundamental programming
technique. A func on in Lisp can call itself as part of its execu on.
3. First-Class Func ons:
o Func ons are first-class ci zens in Lisp, meaning they can be
passed as arguments to other func ons, returned as values, and
stored in variables.
4. Dynamic Typing:
o Lisp is dynamically typed, meaning that variables do not have fixed
types at compile me. The type of a variable is determined at
run me.
5. Macros:
o Lisp allows for powerful metaprogramming via macros, which can
transform code at compile me, enabling the crea on of new
control structures.
6. Garbage Collec on:
o Lisp has built-in automa c memory management via garbage
collec on, which reclaims memory used by objects that are no
longer in use.
Strengths of Lisp:
Flexibility: Lisp’s homoiconicity (code as data) allows for a high degree of
flexibility and metaprogramming.
Extensibility: Lisp allows users to define new language constructs and
create domain-specific languages.
Support for recursion and symbolic manipula on makes it ideal for AI
research and symbolic computa on.
Applica ons of Lisp:
Ar ficial intelligence
Expert systems
Symbolic mathema cal computa on
Computer science research
Robo cs and natural language processing
Prolog is more suitable when solving problems that involve formal logic,
rule-based reasoning, and complex search spaces, such as in knowledge
representa on, natural language processing, or AI decision-making
systems.
Lisp is ideal for tasks that require symbolic manipula on, complex
recursive algorithms, and metaprogramming. It's o en used in AI
research, computer science theory, and systems that need extensive
customiza on or flexibility.
Conclusion:
Prolog and Lisp represent two important paradigms in computer science:
logic programming and symbolic func onal programming, respec vely.
Prolog excels in tasks that require logical reasoning and problem-solving
based on facts and rules, while Lisp's flexibility and powerful support for
recursion and symbolic processing make it a valuable tool in AI and
research. Both languages have had a las ng impact on AI and programming
language design.
2. WRITE SIMPLE FACTS FOR THE STATEMENT USING PROLOG
In these Prolog facts, the predicate represents the rela onship, and the
arguments provide the en es involved in the rela onship. Prolog allows
you to define such facts to represent knowledge about the world, and then
use queries to retrieve informa on based on these facts.
Example Queries
import heapq
# Node class to represent each state in the search problem
class Node:
def __init__(self, state, parent=None, ac on=None, path_cost=0):
self.state = state # the current state
self.parent = parent # parent node
self.ac on = ac on # the ac on taken to get to this state
self.path_cost = path_cost # cost of the path to reach this state
def __lt__(self, other):
return self.path_cost < other.path_cost
# Uniform Cost Search algorithm
def uniform_cost_search(start_state, goal_state, graph):
# Priority Queue to store the nodes to be explored (min-heap based on path
cost)
fron er = []
heapq.heappush(fron er, Node(start_state, path_cost=0))
# Set to keep track of visited states
explored = set()
# While there are nodes to explore
while fron er:
# Get the node with the lowest path cost
node = heapq.heappop(fron er)
# If the goal state is reached, return the path to the goal
if node.state == goal_state:
path = []
while node:
path.append(node.state)
node = node.parent
return path[::-1] # Return reversed path (from start to goal)
# Mark the current node as explored
explored.add(node.state)
# Expand the current node
for ac on, cost, next_state in graph[node.state]:
if next_state not in explored:
child_node = Node(next_state, parent=node, ac on=ac on,
path_cost=node.path_cost + cost)
heapq.heappush(fron er, child_node)
# If no solu on is found
return None
# Example Graph representa on (Adjacency list with costs)
graph = {
'A': [('B', 1, 'B'), ('C', 4, 'C')],
'B': [('A', 1, 'A'), ('C', 2, 'C'), ('D', 5, 'D')],
'C': [('A', 4, 'A'), ('B', 2, 'B'), ('D', 1, 'D')],
'D': [('B', 5, 'B'), ('C', 1, 'C')]
}
# Start and goal states
start = 'A'
goal = 'D'
# Running Uniform Cost Search
path = uniform_cost_search(start, goal, graph)
if path:
print("Path found:", path)
else:
print("No path found")
Output Example:
For the given problem, the output would be:
Path found: ['move_to_B', 'move_to_D', 'move_to_goal']
This indicates that the least-cost path from state 'A' to the goal is:
Move from 'A' to 'B' (cost = 1)
Move from 'B' to 'D' (cost = 2)
Move from 'D' to 'Goal' (cost = 1)
Thus, the total cost is 4, and the solu on path consists of the ac ons
['move_to_B', 'move_to_D', 'move_to_goal'].
4.WRITE PROGRAM TO SOLVE THE MONKEY BANANA PROBLEM
def __hash__(self):
return hash((self.monkey_posi on, self.box_posi on,
self.has_banana))
# Ac on 2: Push the box under the banana if it's not already under the
banana
if not state.box_posi on:
possible_ac ons.append("Push box under banana")
# Ac on 3: Climb onto the box (if it's not already on the box)
if not state.monkey_posi on and state.box_posi on:
possible_ac ons.append("Climb onto box")
# Ac on 4: Get the banana (only if the monkey is on the box and the
box is under the banana)
if state.monkey_posi on and state.box_posi on and not
state.has_banana:
possible_ac ons.append("Get the banana")
explored.add(current_state)
Output:
Goal reached! Final state: Monkey(box), Box(under banana), Has banana
5. WRITE PROGRAM IN PROLOG FOR MEDICAL SCIENCES
% Rule: Diagnose a person with a disease if the person has all symptoms of that
disease.
diagnose_person(Person, Disease) :-
findall(Symptom, disease(Disease, Symptom), Symptoms),
diagnose_with_symptoms(Person, Symptoms),
write(Person), write(' is diagnosed with '), write(Disease), nl.
Output:
?- find_disease(john).
john is diagnosed with flu.
6. WRITE PROBLEM TO SOLVE MATHEMATICAL PROBLEM SUCH AS
CALCULATE FACTORIAL, GENERATE FABONACCI SERIES, ETC
% Base cases
fibonacci(0, 0).
fibonacci(1, 1).
% Recursive case: Fibonacci of N is the sum of the two preceding Fibonacci
numbers
fibonacci(N, Result) :-
N > 1,
N1 is N - 1,
N2 is N - 2,
fibonacci(N1, Result1),
fibonacci(N2, Result2),
Result is Result1 + Result2.
Output:
?- fibonacci(6, Result).
Result = 8.
import itertools
def calculate_total_distance(permuta on, distance_matrix):
total_distance = 0
for i in range(len(permuta on) - 1):
total_distance += distance_matrix[permuta on[i]][permuta on[i + 1]]
total_distance += distance_matrix[permuta on[-1]][permuta on[0]] #
Returning to the star ng city
return total_distance
def traveling_salesman_bruteforce(distance_matrix):
# Get all permuta ons of ci es (excluding the star ng city)
n = len(distance_matrix)
ci es = list(range(n))
# Generate all possible routes
min_route = None
min_distance = float('inf')
# Try every possible route (brute force approach)
for perm in itertools.permuta ons(ci es[1:]): # Start from city 0
route = [ci es[0]] + list(perm)
distance = calculate_total_distance(route, distance_matrix)
# Update the minimum distance and route
if distance < min_distance:
min_distance = distance
min_route = route
return min_route, min_distance
def print_solu on(route, distance):
print("Op mal Route: ", " -> ".join(map(str, route)))
print("Minimum Distance: ", distance)
# Example usage:
# Distance matrix (example with 4 ci es)
# The distance matrix should be symmetric (distance from city A to B is same as
from B to A)
distance_matrix = [
[0, 10, 15, 20],
[10, 0, 35, 25],
[15, 35, 0, 30],
[20, 25, 30, 0]
]
route, distance = traveling_salesman_bruteforce(distance_matrix)
print_solu on(route, distance)
Output:
0 10 15 20
10 0 35 25
15 35 0 30
20 25 30 0
9. WRITE PROGRAM TO SOLVE WATER JUG PROBLEM
Output:
| |
---------
| |
---------
| |
Player X, enter your move (1-9): 1
X| |
---------
| |
---------
| |
Player O, enter your move (1-9): 5
X| |
---------
|O|
---------
| |
Player X, enter your move (1-9): 2
X|X|
---------
|O|
---------
| |
Player O, enter your move (1-9): 9
X|X|
---------
|O|
---------
| |O
Player X, enter your move (1-9): 3
X|X|X
---------
|O|
---------
| |
Player X wins!