Intelligent and Expert Sys Lab File
Intelligent and Expert Sys Lab File
AFFILIATED TO
SEMESTER- VII
SUB-CODE: AI-405P
SECTION:
ENROLLMENT NUMBER:
BRANCH:
INDEX
S.No Name of the Experiment Date Signature Remarks
b. Seema is a girl.
c. Bill likes Cindy.
d. Rose is red.
e. John owns gold.
PROLOG-PROGRAMMING IN LOGIC
PROLOG stands for Programming In Logic – an idea that emerged in the early 1970’s to use
logic as programming language.The early developers of this idea included Robert Kowalski
at Edinburgh ( on the theoretical side ),Marrten van Emden at Edinburgh ( experimental
demonstration) and Alian Colmerauer at Marseilles (implementation ). David D.H. Warren’s
efficient implementation at Edinburgh in the mid - 1970’s greatly contributed to the
popularity of PROLOG.
SYMBOLIC LANGUAGE
FOR EXAMPLE:
a) FACTS:
sister(sue,bill)
parent(ann,sam)
male(jo)
female(riya)
b ) RULES:
To represent the general rule for grandfather, we write:
grandfather(X,Z)
parent(X,Y)
parent(Y,Z)
male(X)
c) QUERIES:
. Once we have a database of facts (and, soon, rules) we can ask questions
about the stored information.
. Suppose we want to know if Turing lectures in course 9020. We can ask:
% prolog -s facts03
(multi-line welcome message) facts03 loaded into Prolog
?- lectures(turing, 9020). "?-" is Prolog's prompt
true. output from Prolog
?- <control-D> hold down control & press D
% to leave Prolog
. Notice that:
o In SWI Prolog, queries are terminated by a full stop.
o To answer this query, Prolog consults its database to see if this is a known fact.
o In example dialogues with Prolog, the text in green italics is what the user
types.
?- lectures(codd, 9020).
false.
Given a database of facts and rules such as that above, we may make queries by typing
after a query a symbol ‘?
’ statements such as: ?
_ Parent(X,sam) X=ann ?
_grandfather(X,Y)
X=jo, Y=sam
Backtracking in Prolog
Backtracking in Prolog 2
. After the first solution is found, Prolog retraces its steps up the tree and looks
for alternative solutions.
. First it looks for other students studying 9311 (but finds none).
. Then it
o backs up
o rebinds Course to 9314,
o goes down the lectures(codd, 9314) branch
o tries studies(Student, 9314),
o finds the other two solutions:
(Course = 9314, Student = jill)
and ( Course = 9 3 1 4 , Student = henry) .
Backtracking in Prolog 3
To picture what happens when Prolog tries to find a solution and backtracks, we draw a
" proof tree":
META PROGRAMMING
A meta program is a program that takes other programs as data. Interpreters and compilers
are examples of meta-programs. Meta-interpreter is a particular kind of metaprogram: an
interpreter for a language written in that language. So a PROLOG meteinterpreter is an
interpreter for PROLOG, itself written in PROLOG.
Applications of Prolog
Code:
# Facts as simple relations
facts = {
'Ram': 'likes mango',
'Seema': 'is a girl',
'Bill': 'likes Cindy',
'Rose': 'is red',
'John': 'owns gold'
}
OUTPUT:
PROGRAM NO .- 3
Write predicates, one converts centigrade temperatures to Fahrenheit, the other checks
if a temperature is below freezing using Python.
Code:
def celsius_to_fahrenheit(celsius):
return (celsius * 9/5) + 32
def is_below_freezing(celsius):
return celsius < 0
temp = 29.84
fahrenheit = celsius to fahrenheit(temp)
print(f"Temperature in Fahrenheit: {fahrenheit}")
if is_below_freezing(temp):
print("The temperature is below freezing.")
else:
print("The temperature is above freezing.")
OUTPUT:
PROGRAM NO- 4
Code:
def is_safe(board, row, col):
for i in range(col):
if board[row][i] == 1:
return False
Code:
def is_safe(board, row, col):
for i in range(col):
if board[row][i] == 1:
return False
for i, j in zip(range(row, - 1, - 1), range(col, - 1, - 1)):
if board[i][j] == 1:
return False
for i, j in zip(range(row, len(board), 1), range(col, - 1, - 1)):
if board[i][j] == 1:
return False
return True
solve 8 queens()
OUTPUT:
PROGRAM NO:-5
Code:
defdfs(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)
graph = {
'A': ['B', 'C'],
'B': ['D', 'E'],
'C': ['F'],
'D': [],
'E': ['F'],
'F': []
}
dfs(graph, 'A')
OUTPUT:
PROGRAM NO:- 6
Code:
import heapq
while pq:
cost, node = heapq.heappop(pq)
if node = = goal:
print(f"Goal {goal} found!")
return
visited.add(node)
print(f"Visiting node {node}")
for neighbor, weight in graph[node]:
if neighbor not in visited:
heapq.heappush(pq, (h[neighbor], neighbor))
graph = {
'A': [('B', 1), ('C', 3)],
'B': [('D', 5), ('E', 6)],
'C': [('F', 7)],
'D': [],
'E': [('F', 4)],
'F': []
}
heuristic = {
'A': 10,
'B': 8,
'C': 5,
'D': 7,
'E': 3,
'F': 0
}
OUTPUT:
PROGRAM NO:- 7
Code:
from collections import deque
def is_solvable(state):
inversions = 0
flat_state = [num for row in state for num in row if num != 0]
for i in range(len(flat state_)):
for j in range(i + 1, len(flat state_)):
if flat_state[i] > flat_state[j]:
inversions += 1
return inversions % 2 = = 0
while queue:
current = queue.popleft()
if current = = goal:
print("Solution found!")
return
# Implement movement logic here (left, right, up, down)
# Expand the state and add new states to the queue
# Check if the state is already visited
print("No solution exists.")
if is_solvable(initial_state):
bfs(initial_state, goal_state)
else:
print("This puzzle is not solvable.")
OUTPUT:
PROGRAM NO:-8
Code:
# Example of robot navigation
def robot_navigation(start, goal):
print(f"Robot starts at {start}")
while start != goal:
if start[0] < goal[0]:
start = (start[0] + 1, start[1])
elif start[0] > goal[0]:
start = (start[0] - 1, start[1])
if start[1] < goal[1]:
start = (start[0], start[1] + 1)
elif start[1] > goal[1]:
start = (start[0], start[1] - 1)
print(f"Robot moves to {start}")
print("Robot reached the goal.")
OUTPUT:
PROGRAM NO:-9
Code:
from itertools import permutations
graph = {
'A': {'B': 10, 'C': 15, 'D': 20},
'B': {'A': 10, 'C': 35, 'D': 25},
'C': {'A': 15, 'B': 35, 'D': 30},
'D': {'A': 20, 'B': 25, 'C': 30}
}
OUTPUT:
PROGRAM NO:-10
Code:
class KnowledgeBase:
def__init (self):
# Initialize an empty set for facts and an empty list for rules
self.facts = set()
self.rules = []
def print_facts(self):
"""
Prints all the facts currently in the knowledge base.
"""
print("\nCurrent Facts in Knowledge Base:")
for fact in self.facts:
print(fact)
def print_rules(self):
"""
Prints all the rules currently in the knowledge base.
"""
print("\nCurrent Rules in Knowledge Base:")
for rule in self.rules:
print(rule)
# Example usage:
if __name__ == "__main__":
# Create an instance of the KnowledgeBase
kb = KnowledgeBase()
OUTPUT:
Program No:- 11
Code:
class KnowledgeBase:
def__init (self):
self.facts = set() # A set to store known facts
self.rules = [] # A list to store inference rules
def infer(self):
inferred = True
while inferred:
inferred = False
for rule in self.rules:
if rule():
inferred = True
def rule_animal_is_bird():
if "has_feathers" in kb.facts and "lays_eggs" in kb.facts:
if "is_bird" not in kb.facts:
kb.add_fact("is_bird")
return True
return False
def rule_is_warm_blooded():
if "is_mammal" in kb.facts or "is_bird" in kb.facts:
if "is_warm_blooded" not in kb.facts:
kb.add_fact("is_warm_blooded")
return True
return False
# Add rules to the knowledge base
kb.add_rule(rule_animal_is_mammal)
kb.add_rule(rule_animal_is_bird)
kb.add_rule(rule_is_warm_blooded)
OUTPUT: