Uploaded by Ishan Anthony

LabManual 1852 Content Document 20221029123629PM

advertisement
B.M.S. INSTITUTE OF TECHNOLOGY & MANAGEMENT
Avalahalli, Doddaballapur Main Road, Yelahanka, Bangalore, India - 560064
(Autonomous Under VTU)
(Accredited By National Assessment & Accreditation Council (NAAC)) (Approved by
AICTE, New Delhi & Affiliated to Visvesvaraya Technological University, Belagavi)
T&
M
-A
I&
M
L
Department of
Artificial Intelligence & Machine Learning
SI
Lab Manual
BM
Artificial Intelligence Laboratory
18AIL57
Prepared By:
Dr. Pradeep K R & Dr. Vishwa Kiran S
Institution Vision & Mission
Vision
• To emerge as one of the finest technical institutions of higher learning to
develop engineering professionals who are technically competent, ethical and
environment friendly for betterment of the society.
Mission
• Accomplish stimulating learning environment through high quality academic
I&
M
L
instruction, innovation and industry-institute interface.
-A
Department Vision & Mission
Vision
T&
M
• To develop professionals equipped to build sustainable and intelligent
solutions that effectively interact with the natural intelligence towards creating
ethics.
BM
Mission
SI
a digitally empowered environment for future generations, safeguarding social
• To enable students with the spirit and power of interdisciplinary acumen by
integrating a world of knowledge into a world of intelligent systems and
subsystems.
• Boost academic outcome through place-based education and collaborations
with established research labs and industries.
• Encourage entrepreneurship efforts among students and develop them into
great leaders
Artificial Intelligence Laboratory 18AIL57
5 th Sem
Dept. Of AI & ML
ARTIFICIAL INTELLIGENCE LABORATORY
Subject Code
18AIL57
Number of Contact hours/Week
0:2:2
Total Number of Lab Contact Hours
CIE Marks
SEE Marks
Exam Hours
40
60
3 Hrs
******************************************************************************
Course Learning Objectives: This course will enable students to:
 Implement and evaluate AI algorithms in Python programming language.
-A
I&
M
L
Descriptions (if any):
Installation procedure of the required software must be demonstrated, carried out in groups
and documented in the journal.
Programs List:
Practicing Problems in Python (Students can be encouraged to practice good number of
practice problems, some practice problems are listed here)
******************************************************************************
1. (a) Write a python program to print the multiplication table for the given number
(b) Write a python program to check whether the given number is prime or not?
T&
M
(c) Write a python program to find factorial of the given number?
2. (a) Write a python program to implement List operations (Nested List, Length,
Concatenation, Membership, Iteration, Indexing and Slicing)
SI
(b) Write a python program to implement List methods (Add, Append, Extend & Delete).
3. Write a python program to implement simple Chatbot with minimum 10 conversations
BM
4. Write a python program to Illustrate Different Set Operations
5. (a)Write a python program to implement a function that counts the number of times a
string(s1) occurs in another string(s2).
(b)Write a program to illustrate Dictionary operations ([], in, traversal) and methods:
keys (), values (), items ()
Dr. Pradeep K R & Dr. Vishwa Kiran S
BMSIT&M-Bengaluru-64
Page 1 of 42
Artificial Intelligence Laboratory 18AIL57
5 th Sem
Dept. Of AI & ML
*****************************************************************************
****AI Problems to be implemented in Python****
*****************************************************************************
1. Implement and Demonstrate Depth First Search Algorithm on Water Jug Problem,
Import collections.
2. Implement and Demonstrate Best First Search Algorithm on any AI problem.
3. Implement AO* Search algorithm.
4. Solve 8-Queens Problem with suitable assumptions.
5. Implementation of TSP using heuristic approach.
6.Implementation of the problem-solving strategies: either using Forward Chaining or
L
Backward Chaining.
M
7.Implement resolution principle on FOPL related problems.
I&
8.Implement any Game and demonstrate the Game playing strategies.
-A
Laboratory Outcomes: The student should be able to:
 Implement and demonstrate AI algorithms.
 Evaluate different algorithms.
BM
SI
T&
M
Conduct of Practical Examination:
Experiment distribution
 For laboratories having only one part: Students are allowed to pick one experiment from the
lot with equal opportunity.
 For laboratories having PART A and PART B: Students are allowed to pick one experiment
from PART A and one experiment from PART B, with equal opportunity.
 Change of experiment is allowed only once and marks allotted for procedure to be made
zero of the changed part only.
 Marks Distribution (Subjected to change in accordance with university regulations)
i) For laboratories having only one part – Procedure + Execution + Viva-Voce: 15+70+15 = 100
Marks
j) For laboratories having PART A and PART B
i. Part A – Procedure + Execution + Viva = 6 + 28 + 6 = 40 Marks
ii. Part B – Procedure + Execution + Viva = 9 + 42 + 9 = 60 Marks
*****************************************************************************
Dr. Pradeep K R & Dr. Vishwa Kiran S
BMSIT&M-Bengaluru-64
Page 2 of 42
Artificial Intelligence Laboratory 18AIL57
5 th Sem
Dept. Of AI & ML
****AI Problems to be implemented in Python****
*****************************************************************************
1. Implement and Demonstrate Depth First Search Algorithm on Water Jug Problem.
import queue
import time
import random
dfsq = queue.Queue()
I&
def printnode(self):
print("(", self.x, ",", self.y, ")")
M
L
class node:
def __init__(self, data):
self.x = 0
self.y = 0
self.parent = data
BM
SI
T&
M
-A
def generateAllSuccessors(cnode):
list1 = []
list_rule = []
while len(list_rule) < 8:
rule_no = random.randint(1, 8)
if (not rule_no in list_rule):
list_rule.append(rule_no)
nextnode = operation(cnode, rule_no)
if nextnode != None and not IsNodeInlist(nextnode, visitednodelist):
list1.append(nextnode)
"""for rule in range (1,9):
nextnode = operation(cnode,rule) #current node
if nextnode != None :
list1.append(nextnode)"""
return list1
def operation(cnode, rule):
x = cnode.x
y = cnode.y
if rule == 1:c
if x < maxjug1:
x = maxjug1
else:
return None
elif rule == 2:
if y < maxjug2:
Dr. Pradeep K R & Dr. Vishwa Kiran S
BMSIT&M-Bengaluru-64
Page 3 of 42
Dept. Of AI & ML
M
I&
-A
BM
SI
T&
M
y = maxjug2
else:
return None
elif rule == 3:
if x > 0:
x=0
else:
return None
elif rule == 4:
if y > 0:
y=0
else:
return None
elif rule == 5:
if x + y >= maxjug1:
y = y - (maxjug1 - x)
x = maxjug1
else:
return None
elif rule == 6:
if x + y >= maxjug2:
x = x - (maxjug2 - y)
y = maxjug2
else:
return None
elif rule == 7:
if x + y < maxjug1:
x=x+y
y=0
else:
return None
elif rule == 8:
if x + y < maxjug2:
x=0
y=x+y
else:
return None
if (x == cnode.x and y == cnode.y):
return None
nextnode = node(cnode)
nextnode.x = x
nextnode.y = y
nextnode.parent = cnode
return nextnode
5 th Sem
L
Artificial Intelligence Laboratory 18AIL57
Dr. Pradeep K R & Dr. Vishwa Kiran S
BMSIT&M-Bengaluru-64
Page 4 of 42
Artificial Intelligence Laboratory 18AIL57
5 th Sem
Dept. Of AI & ML
def pushlist(list1):
for m in list1:
dfsq.put(m)
def popnode():
if (dfsq.empty()):
return None
else:
return dfsq.get()
I&
M
L
def isGoalNode(cnode, gnode):
if (cnode.x == gnode.x and cnode.y == gnode.y):
return True
return False
-A
visitednodelist = []
BM
SI
T&
M
def dfsMain(initialNode, GoalNode):
dfsq.put(initialNode)
while not dfsq.empty():
visited_node = popnode()
print("Pop node:")
visited_node.printnode()
if isGoalNode(visited_node, GoalNode):
return visited_node
successor_nodes = generateAllSuccessors(visited_node)
pushlist(successor_nodes)
return None
def IsNodeInlist(node, list1):
for m in list1:
if (node.x == m.x and node.y == m.y):
return True
return False
def printpath(cnode):
temp = cnode
list2 = []
while (temp != None):
list2.append(temp)
Dr. Pradeep K R & Dr. Vishwa Kiran S
BMSIT&M-Bengaluru-64
Page 5 of 42
Artificial Intelligence Laboratory 18AIL57
5 th Sem
Dept. Of AI & ML
temp = temp.parent
list2.reverse()
for i in list2:
i.printnode()
print("Path Cost:", len(list2))
M
BM
SI
T&
M
-A
I&
list2 = []
maxjug1 = int(input("Enter value of maxjug1:"))
maxjug2 = int(input("Enter value of maxjug2:"))
initialNode = node(None)
initialNode.x = 0
initialNode.y = 0
initialNode.parent = None
GoalNode = node(None)
GoalNode.x = int(input("Enter value of Goal in jug1:"))
GoalNode.y = 0
GoalNode.parent = None
start_time = time.time()
solutionNode = dfsMain(initialNode, GoalNode)
end_time = time.time()
if (solutionNode != None):
print("Solution can Found:")
else:
print("Solution can't be found.")
printpath(solutionNode)
diff = end_time - start_time
print("Execution Time:", diff * 1000, "ms")
L
if __name__ == '__main__':
Output:
Enter value of maxjug1:5
Enter value of maxjug2:3
Enter value of Goal in jug1:4
Solution can Found:
(0,0)
(0,3)
(3,0)
(3,3)
(5,1)
(0,1)
(1,0)
(1,3)
(4,0)
Path Cost: 9
Dr. Pradeep K R & Dr. Vishwa Kiran S
BMSIT&M-Bengaluru-64
Page 6 of 42
Artificial Intelligence Laboratory 18AIL57
5 th Sem
Dept. Of AI & ML
2. Implement and Demonstrate Best First Search Algorithm on any AI problem-Missionaries
(M) and Cannibals (C).
import copy
# The problem starts with 3 Missionaries (M) and 3 Cannibals (C) in the left side of a river
(leftCoast) trying to
# cross with a boat(B) going to the right side (rightCoast) with the restriction that never the
number of Cannibals
# will outnumber the Missionaries on either side
L
class CoastState:
I&
M
def __init__(self, c, m):
self.cannibals = c
self.missionaries = m
T&
M
-A
# This is an intermediate state of Coast where the missionaries have to outnumber the
cannibals
def valid_coast(self):
if self.missionaries >= self.cannibals or self.missionaries == 0:
return True
else:
return False
BM
SI
def goal_coast(self):
if self.cannibals == 3 and self.missionaries == 3:
return True
else:
return False
class GameState:
def __init__(self, data):
self.data = data
self.parent = None
# Creating the Search Tree
def building_tree(self):
children = []
coast = ""
across_coast = ""
temp = copy.deepcopy(self.data)
Dr. Pradeep K R & Dr. Vishwa Kiran S
BMSIT&M-Bengaluru-64
Page 7 of 42
Artificial Intelligence Laboratory 18AIL57
5 th Sem
Dept. Of AI & ML
if self.data["boat"] == "left":
coast = "left"
across_coast = "right"
elif self.data["boat"] == "right":
coast = "right"
across_coast = "left"
M
L
# MOVING 2 CANNIBALS (CC)
if temp[coast].cannibals >= 2:
temp[coast].cannibals = temp[coast].cannibals - 2
temp[across_coast].cannibals = temp[across_coast].cannibals + 2
temp["boat"] = across_coast
if temp[coast].valid_coast() and temp[across_coast].valid_coast():
child = GameState(temp)
child.parent = self
children.append(child)
SI
T&
M
-A
I&
temp = copy.deepcopy(self.data)
# MOVING 2 MISSIONARIES (MM)
if temp[coast].missionaries >= 2:
temp[coast].missionaries = temp[coast].missionaries - 2
temp[across_coast].missionaries = temp[across_coast].missionaries + 2
temp["boat"] = across_coast
if temp[coast].valid_coast() and temp[across_coast].valid_coast():
child = GameState(temp)
child.parent = self
children.append(child)
BM
temp = copy.deepcopy(self.data)
# MOVING 1 CANNIBAL (C)
if temp[coast].cannibals >= 1:
temp[coast].cannibals = temp[coast].cannibals - 1
temp[across_coast].cannibals = temp[across_coast].cannibals + 1
temp["boat"] = across_coast
if temp[coast].valid_coast() and temp[across_coast].valid_coast():
child = GameState(temp)
child.parent = self
children.append(child)
temp = copy.deepcopy(self.data)
# MOVING 1 MISSIONARY (M)
if temp[coast].missionaries >= 1:
temp[coast].missionaries = temp[coast].missionaries - 1
temp[across_coast].missionaries = temp[across_coast].missionaries + 1
temp["boat"] = across_coast
if temp[coast].valid_coast() and temp[across_coast].valid_coast():
Dr. Pradeep K R & Dr. Vishwa Kiran S
BMSIT&M-Bengaluru-64
Page 8 of 42
Artificial Intelligence Laboratory 18AIL57
5 th Sem
Dept. Of AI & ML
child = GameState(temp)
child.parent = self
children.append(child)
I&
M
L
temp = copy.deepcopy(self.data)
# MOVING 1 CANNIBAL AND 1 MISSIONARY (CM && MM)
if temp[coast].missionaries >= 1 and temp[coast].cannibals >= 1:
temp[coast].missionaries = temp[coast].missionaries - 1
temp[across_coast].missionaries = temp[across_coast].missionaries + 1
temp[coast].cannibals = temp[coast].cannibals - 1
temp[across_coast].cannibals = temp[across_coast].cannibals + 1
temp["boat"] = across_coast
if temp[coast].valid_coast() and temp[across_coast].valid_coast():
child = GameState(temp)
child.parent = self
children.append(child)
return children
T&
M
-A
def breadth_first_search():
left = CoastState(3, 3)
right = CoastState(0, 0)
root_data = {"left": left, "right": right, "boat": "left"}
SI
explored = []
nodes = []
path = []
nodes.append(GameState(root_data))
BM
while len(nodes) > 0:
g = nodes.pop(0)
explored.append(g)
if g.data["right"].goal_coast():
path.append(g)
return g
else:
next_children = g.building_tree()
for x in next_children:
if (x not in nodes) or (x not in explored):
nodes.append(x)
return None
def print_path(g):
path = [g]
Dr. Pradeep K R & Dr. Vishwa Kiran S
BMSIT&M-Bengaluru-64
Page 9 of 42
Artificial Intelligence Laboratory 18AIL57
5 th Sem
Dept. Of AI & ML
I&
M
L
while g.parent:
g = g.parent
path.append(g)
print("
" + "Left Side" + "
" + "Right Side" + "
" + "Boat ")
print(
"
Cannibals" + " Missionaries" + "
" + "Cannibals" + "
Missionaries" + "
Boat Position")
counter = 0
for p in reversed(path):
print("State " + str(counter) + " Left C: " + str(p.data["left"].cannibals) + ". Left M: " +
str(
p.data["left"].missionaries) + ". | Right C: " + str(
p.data["right"].cannibals) + ". Right M: " + str(p.data["right"].missionaries) + ". |
Boat: " + str(
p.data["boat"]))
counter = counter + 1
print("End of Path!")
Output:
SI
if __name__ == "__main__":
main()
T&
M
-A
def main():
solution = breadth_first_search()
print("Missionaries and Cannibals AI Problem Solution using Breath - First Search:")
print_path(solution)
BM
Graph - 1
HEURISTIC VALUES : {'A': 1, 'B': 6, 'C': 2, 'D': 12, 'E': 2, 'F': 1, 'G': 5, 'H': 7, 'I': 7, 'J': 1}
SOLUTION GRAPH : {}
PROCESSING NODE : A
----------------------------------------------------------------------------------------10 ['B', 'C']
HEURISTIC VALUES : {'A': 10, 'B': 6, 'C': 2, 'D': 12, 'E': 2, 'F': 1, 'G': 5, 'H': 7, 'I': 7, 'J': 1}
SOLUTION GRAPH : {}
PROCESSING NODE : B
----------------------------------------------------------------------------------------6 ['G']
HEURISTIC VALUES : {'A': 10, 'B': 6, 'C': 2, 'D': 12, 'E': 2, 'F': 1, 'G': 5, 'H': 7, 'I': 7, 'J': 1}
SOLUTION GRAPH : {}
PROCESSING NODE : A
----------------------------------------------------------------------------------------10 ['B', 'C']
Dr. Pradeep K R & Dr. Vishwa Kiran S
BMSIT&M-Bengaluru-64
Page 10 of 42
Artificial Intelligence Laboratory 18AIL57
5 th Sem
Dept. Of AI & ML
BM
SI
T&
M
-A
I&
M
L
HEURISTIC VALUES : {'A': 10, 'B': 6, 'C': 2, 'D': 12, 'E': 2, 'F': 1, 'G': 5, 'H': 7, 'I': 7, 'J': 1}
SOLUTION GRAPH : {}
PROCESSING NODE : G
----------------------------------------------------------------------------------------8 ['I']
HEURISTIC VALUES : {'A': 10, 'B': 6, 'C': 2, 'D': 12, 'E': 2, 'F': 1, 'G': 8, 'H': 7, 'I': 7, 'J': 1}
SOLUTION GRAPH : {}
PROCESSING NODE : B
----------------------------------------------------------------------------------------8 ['H']
HEURISTIC VALUES : {'A': 10, 'B': 8, 'C': 2, 'D': 12, 'E': 2, 'F': 1, 'G': 8, 'H': 7, 'I': 7, 'J': 1}
SOLUTION GRAPH : {}
PROCESSING NODE : A
----------------------------------------------------------------------------------------12 ['B', 'C']
HEURISTIC VALUES : {'A': 12, 'B': 8, 'C': 2, 'D': 12, 'E': 2, 'F': 1, 'G': 8, 'H': 7, 'I': 7, 'J': 1}
SOLUTION GRAPH : {}
PROCESSING NODE : I
----------------------------------------------------------------------------------------0 []
HEURISTIC VALUES : {'A': 12, 'B': 8, 'C': 2, 'D': 12, 'E': 2, 'F': 1, 'G': 8, 'H': 7, 'I': 0, 'J': 1}
SOLUTION GRAPH : {'I': []}
PROCESSING NODE : G
----------------------------------------------------------------------------------------1 ['I']
HEURISTIC VALUES : {'A': 12, 'B': 8, 'C': 2, 'D': 12, 'E': 2, 'F': 1, 'G': 1, 'H': 7, 'I': 0, 'J': 1}
SOLUTION GRAPH : {'I': [], 'G': ['I']}
PROCESSING NODE : B
----------------------------------------------------------------------------------------2 ['G']
HEURISTIC VALUES : {'A': 12, 'B': 2, 'C': 2, 'D': 12, 'E': 2, 'F': 1, 'G': 1, 'H': 7, 'I': 0, 'J': 1}
SOLUTION GRAPH : {'I': [], 'G': ['I'], 'B': ['G']}
PROCESSING NODE : A
----------------------------------------------------------------------------------------6 ['B', 'C']
HEURISTIC VALUES : {'A': 6, 'B': 2, 'C': 2, 'D': 12, 'E': 2, 'F': 1, 'G': 1, 'H': 7, 'I': 0, 'J': 1}
SOLUTION GRAPH : {'I': [], 'G': ['I'], 'B': ['G']}
PROCESSING NODE : C
----------------------------------------------------------------------------------------2 ['J']
HEURISTIC VALUES : {'A': 6, 'B': 2, 'C': 2, 'D': 12, 'E': 2, 'F': 1, 'G': 1, 'H': 7, 'I': 0, 'J': 1}
SOLUTION GRAPH : {'I': [], 'G': ['I'], 'B': ['G']}
PROCESSING NODE : A
----------------------------------------------------------------------------------------6 ['B', 'C']
HEURISTIC VALUES : {'A': 6, 'B': 2, 'C': 2, 'D': 12, 'E': 2, 'F': 1, 'G': 1, 'H': 7, 'I': 0, 'J': 1}
Dr. Pradeep K R & Dr. Vishwa Kiran S
BMSIT&M-Bengaluru-64
Page 11 of 42
Artificial Intelligence Laboratory 18AIL57
5 th Sem
Dept. Of AI & ML
BM
SI
T&
M
-A
I&
M
L
SOLUTION GRAPH : {'I': [], 'G': ['I'], 'B': ['G']}
PROCESSING NODE : J
----------------------------------------------------------------------------------------0 []
HEURISTIC VALUES : {'A': 6, 'B': 2, 'C': 2, 'D': 12, 'E': 2, 'F': 1, 'G': 1, 'H': 7, 'I': 0, 'J': 0}
SOLUTION GRAPH : {'I': [], 'G': ['I'], 'B': ['G'], 'J': []}
PROCESSING NODE : C
----------------------------------------------------------------------------------------1 ['J']
HEURISTIC VALUES : {'A': 6, 'B': 2, 'C': 1, 'D': 12, 'E': 2, 'F': 1, 'G': 1, 'H': 7, 'I': 0, 'J': 0}
SOLUTION GRAPH : {'I': [], 'G': ['I'], 'B': ['G'], 'J': [], 'C': ['J']}
PROCESSING NODE : A
----------------------------------------------------------------------------------------5 ['B', 'C']
FOR GRAPH SOLUTION, TRAVERSE THE GRAPH FROM THE START NODE: A
-----------------------------------------------------------{'I': [], 'G': ['I'], 'B': ['G'], 'J': [], 'C': ['J'], 'A': ['B', 'C']}
-----------------------------------------------------------Graph - 2
HEURISTIC VALUES : {'A': 1, 'B': 6, 'C': 12, 'D': 10, 'E': 4, 'F': 4, 'G': 5, 'H': 7}
SOLUTION GRAPH : {}
PROCESSING NODE : A
----------------------------------------------------------------------------------------11 ['D']
HEURISTIC VALUES : {'A': 11, 'B': 6, 'C': 12, 'D': 10, 'E': 4, 'F': 4, 'G': 5, 'H': 7}
SOLUTION GRAPH : {}
PROCESSING NODE : D
----------------------------------------------------------------------------------------10 ['E', 'F']
HEURISTIC VALUES : {'A': 11, 'B': 6, 'C': 12, 'D': 10, 'E': 4, 'F': 4, 'G': 5, 'H': 7}
SOLUTION GRAPH : {}
PROCESSING NODE : A
----------------------------------------------------------------------------------------11 ['D']
HEURISTIC VALUES : {'A': 11, 'B': 6, 'C': 12, 'D': 10, 'E': 4, 'F': 4, 'G': 5, 'H': 7}
SOLUTION GRAPH : {}
PROCESSING NODE : E
----------------------------------------------------------------------------------------0 []
HEURISTIC VALUES : {'A': 11, 'B': 6, 'C': 12, 'D': 10, 'E': 0, 'F': 4, 'G': 5, 'H': 7}
SOLUTION GRAPH : {'E': []}
PROCESSING NODE : D
----------------------------------------------------------------------------------------6 ['E', 'F']
HEURISTIC VALUES : {'A': 11, 'B': 6, 'C': 12, 'D': 6, 'E': 0, 'F': 4, 'G': 5, 'H': 7}
SOLUTION GRAPH : {'E': []}
Dr. Pradeep K R & Dr. Vishwa Kiran S
BMSIT&M-Bengaluru-64
Page 12 of 42
Artificial Intelligence Laboratory 18AIL57
5 th Sem
Dept. Of AI & ML
BM
SI
T&
M
-A
I&
M
L
PROCESSING NODE : A
----------------------------------------------------------------------------------------7 ['D']
HEURISTIC VALUES : {'A': 7, 'B': 6, 'C': 12, 'D': 6, 'E': 0, 'F': 4, 'G': 5, 'H': 7}
SOLUTION GRAPH : {'E': []}
PROCESSING NODE : F
----------------------------------------------------------------------------------------0 []
HEURISTIC VALUES : {'A': 7, 'B': 6, 'C': 12, 'D': 6, 'E': 0, 'F': 0, 'G': 5, 'H': 7}
SOLUTION GRAPH : {'E': [], 'F': []}
PROCESSING NODE : D
----------------------------------------------------------------------------------------2 ['E', 'F']
HEURISTIC VALUES : {'A': 7, 'B': 6, 'C': 12, 'D': 2, 'E': 0, 'F': 0, 'G': 5, 'H': 7}
SOLUTION GRAPH : {'E': [], 'F': [], 'D': ['E', 'F']}
PROCESSING NODE : A
----------------------------------------------------------------------------------------3 ['D']
FOR GRAPH SOLUTION, TRAVERSE THE GRAPH FROM THE START NODE: A
-----------------------------------------------------------{'E': [], 'F': [], 'D': ['E', 'F'], 'A': ['D']}
------------------------------------------------------------
Dr. Pradeep K R & Dr. Vishwa Kiran S
BMSIT&M-Bengaluru-64
Page 13 of 42
Artificial Intelligence Laboratory 18AIL57
5 th Sem
Dept. Of AI & ML
3. Implement AO* Search algorithm.
M
def applyAOStar(self): # starts a recursive AO* algorithm
self.aoStar(self.start, False)
L
class Graph:
def __init__(self, graph, heuristicNodeList, startNode): #instantiate graph object with graph
topology, heuristic values, start node
self.graph = graph
self.H=heuristicNodeList
self.start=startNode
self.parent={}
self.status={}
self.solutionGraph={}
-A
I&
def getNeighbors(self, v): # gets the Neighbors of a given node
return self.graph.get(v,'')
T&
M
def getStatus(self,v): # return the status of a given node
return self.status.get(v,0)
def setStatus(self,v, val): # set the status of a given node
self.status[v]=val
BM
SI
def getHeuristicNodeValue(self, n):
return self.H.get(n,0) # always return the heuristic value of a given node
def setHeuristicNodeValue(self, n, value):
self.H[n]=value # set the revised heuristic value of a given node
def printSolution(self):
print("FOR GRAPH SOLUTION, TRAVERSE THE GRAPH FROM THE START
NODE:",self.start)
print("------------------------------------------------------------")
print(self.solutionGraph)
print("------------------------------------------------------------")
def computeMinimumCostChildNodes(self, v): # Computes the Minimum Cost of child nodes
of a given node v
minimumCost=0
Dr. Pradeep K R & Dr. Vishwa Kiran S
BMSIT&M-Bengaluru-64
Page 14 of 42
Artificial Intelligence Laboratory 18AIL57
5 th Sem
Dept. Of AI & ML
T&
M
-A
I&
M
L
costToChildNodeListDict={}
costToChildNodeListDict[minimumCost]=[]
flag=True
for nodeInfoTupleList in self.getNeighbors(v): # iterate over all the set of child node/s
cost=0
nodeList=[]
for c, weight in nodeInfoTupleList:
cost=cost+self.getHeuristicNodeValue(c)+weight
nodeList.append(c)
if flag==True: # initialize Minimum Cost with the cost of first set of child node/s
minimumCost=cost
costToChildNodeListDict[minimumCost]=nodeList # set the Minimum Cost child
node/s
flag=False
else: # checking the Minimum Cost nodes with the current Minimum Cost
if minimumCost>cost:
minimumCost=cost
costToChildNodeListDict[minimumCost]=nodeList # set the Minimum Cost child
node/s
return minimumCost, costToChildNodeListDict[minimumCost] # return Minimum Cost
and Minimum Cost child node/s
BM
SI
def aoStar(self, v, backTracking): # AO* algorithm for a start node and backTracking status
flag
print("HEURISTIC VALUES :", self.H)
print("SOLUTION GRAPH :", self.solutionGraph)
print("PROCESSING NODE :", v)
print("-----------------------------------------------------------------------------------------")
if self.getStatus(v) >= 0: # if status node v >= 0, compute Minimum Cost nodes of v
minimumCost, childNodeList = self.computeMinimumCostChildNodes(v)
print(minimumCost, childNodeList)
self.setHeuristicNodeValue(v, minimumCost)
self.setStatus(v,len(childNodeList))
solved=True # check the Minimum Cost nodes of v are solved
for childNode in childNodeList:
self.parent[childNode]=v
if self.getStatus(childNode)!=-1:
solved=solved & False
if solved==True: # if the Minimum Cost nodes of v are solved, set the current node status
as solved(-1)
Dr. Pradeep K R & Dr. Vishwa Kiran S
BMSIT&M-Bengaluru-64
Page 15 of 42
Artificial Intelligence Laboratory 18AIL57
5 th Sem
Dept. Of AI & ML
L
self.setStatus(v,-1)
self.solutionGraph[v]=childNodeList # update the solution graph with the solved nodes
which may be a part of solution
if v!=self.start: # check the current node is the start node for backtracking the current
node value
self.aoStar(self.parent[v], True) # backtracking the current node value with
backtracking status set to true
if backTracking==False: # check the current call is not for backtracking
for childNode in childNodeList: # for each Minimum Cost child node
self.setStatus(childNode,0) # set the status of child node to 0(needs exploration)
self.aoStar(childNode, False) # Minimum Cost child node is further explored with
backtracking status as false
BM
SI
G1= Graph(graph1, h1, 'A')
G1.applyAOStar()
G1.printSolution()
T&
M
-A
I&
M
#for simplicity we ll consider heuristic distances given
print ("Graph - 1")
h1 = {'A': 1, 'B': 6, 'C': 2, 'D': 12, 'E': 2, 'F': 1, 'G': 5, 'H': 7, 'I': 7, 'J': 1}
graph1 = {
'A': [[('B', 1), ('C', 1)], [('D', 1)]],
'B': [[('G', 1)], [('H', 1)]],
'C': [[('J', 1)]],
'D': [[('E', 1), ('F', 1)]],
'G': [[('I', 1)]]
}
print ("Graph - 2")
h2 = {'A': 1, 'B': 6, 'C': 12, 'D': 10, 'E': 4, 'F': 4, 'G': 5, 'H': 7} # Heuristic values of Nodes
graph2 = { # Graph of Nodes and Edges
'A': [[('B', 1), ('C', 1)], [('D', 1)]], # Neighbors of Node 'A', B, C & D with repective weights
'B': [[('G', 1)], [('H', 1)]], # Neighbors are included in a list of lists
'D': [[('E', 1), ('F', 1)]] # Each sublist indicate a "OR" node or "AND" nodes
}
G2 = Graph(graph2, h2, 'A') # Instantiate Graph object with graph, heuristic values and start
Node
G2.applyAOStar() # Run the AO* algorithm
G2.printSolution() # Print the solution graph as output of the AO* algorithm search
Dr. Pradeep K R & Dr. Vishwa Kiran S
BMSIT&M-Bengaluru-64
Page 16 of 42
Artificial Intelligence Laboratory 18AIL57
5 th Sem
Dept. Of AI & ML
4. Solve 8-Queens Problem with suitable assumptions
#Number of queens
print ("Enter the number of queens")
N = int(input())
#chessboard
#NxN matrix with all elements 0
L
board = [[0]*N for _ in range(N)]
M
def is_attack(i, j):
for k in range(0,N):
-A
if board[i][k]==1 or board[k][j]==1:
I&
#checking if there is a queen in row or column
#checking diagonals
for k in range(0,N):
for l in range(0,N):
T&
M
return True
SI
if (k+l==i+j) or (k-l==i-j):
if board[k][l]==1:
BM
return True
return False
def N_queen(n):
#if n is 0, solution found
if n==0:
return True
for i in range(0,N):
for j in range(0,N):
'''checking if we can place a queen here or not
queen will not be placed if the place is being attacked
Dr. Pradeep K R & Dr. Vishwa Kiran S
BMSIT&M-Bengaluru-64
Page 17 of 42
Artificial Intelligence Laboratory 18AIL57
5 th Sem
Dept. Of AI & ML
or already occupied'''
if (not(is_attack(i,j))) and (board[i][j]!=1):
board[i][j] = 1
#recursion
#wether we can put the next queen with this arrangment or not
if N_queen(n-1)==True:
return True
board[i][j] = 0
M
L
return False
I&
N_queen(N)
for i in board:
-A
print (i)
8
Output:
BM
[1, 0, 0, 0, 0, 0, 0, 0]
SI
Enter the number of queens
T&
M
Output:
[0, 0, 0, 0, 1, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 1]
[0, 0, 0, 0, 0, 1, 0, 0]
[0, 0, 1, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 1, 0]
[0, 1, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 1, 0, 0, 0, 0]
Dr. Pradeep K R & Dr. Vishwa Kiran S
BMSIT&M-Bengaluru-64
Page 18 of 42
Artificial Intelligence Laboratory 18AIL57
5 th Sem
Dept. Of AI & ML
5. Implementation of TSP using heuristic approach.
#5:Implementation of TSP using heuristic approach .
# Traveling Salesman Problem using
# Branch and Bound.
import math
maxsize = float('inf')
M
I&
-A
BM
SI
T&
M
# Function to find the minimum edge cost
# having an end at the vertex i
def firstMin(adj, i):
min = maxsize
for k in range(N):
if adj[i][k] < min and i != k:
min = adj[i][k]
return min
# function to find the second minimum edge
# cost having an end at the vertex i
def secondMin(adj, i):
first, second = maxsize, maxsize
for j in range(N):
if i == j:
continue
if adj[i][j] <= first:
second = first
first = adj[i][j]
L
# Function to copy temporary solution
# to the final solution
def copyToFinal(curr_path):
final_path[:N + 1] = curr_path[:]
final_path[N] = curr_path[0]
elif(adj[i][j] <= second and
adj[i][j] != first):
second = adj[i][j]
return second
# function that takes as arguments:
# curr_bound -> lower bound of the root node
# curr_weight-> stores the weight of the path so far
# level-> current level while moving
# in the search space tree
# curr_path[] -> where the solution is being stored
Dr. Pradeep K R & Dr. Vishwa Kiran S
BMSIT&M-Bengaluru-64
Page 19 of 42
Artificial Intelligence Laboratory 18AIL57
5 th Sem
Dept. Of AI & ML
# which would later be copied to final_path[]
def TSPRec(adj, curr_bound, curr_weight,
level, curr_path, visited):
global final_res
# base case is when we have reached level N
# which means we have covered all the nodes once
if level == N:
# check if there is an edge from
# last vertex in path back to the first vertex
if adj[curr_path[level - 1]][curr_path[0]] != 0:
[curr_path[0]]
I&
if curr_res < final_res:
copyToFinal(curr_path)
final_res = curr_res
M
L
# curr_res has the total weight
# of the solution we got
curr_res = curr_weight + adj[curr_path[level - 1]]\
BM
SI
T&
M
-A
return
# for any other level iterate for all vertices
# to build the search space tree recursively
for i in range(N):
# Consider next vertex if it is not same
# (diagonal entry in adjacency matrix and
# not visited already)
if (adj[curr_path[level-1]][i] != 0 and
visited[i] == False):
temp = curr_bound
curr_weight += adj[curr_path[level - 1]][i]
# different computation of curr_bound
# for level 2 from the other levels
if level == 1:
curr_bound -= ((firstMin(adj, curr_path[level - 1]) +
firstMin(adj, i)) / 2)
else:
curr_bound -= ((secondMin(adj, curr_path[level - 1]) +
firstMin(adj, i)) / 2)
# curr_bound + curr_weight is the actual lower bound
# for the node that we have arrived on.
# If current lower bound < final_res,
# we need to explore the node further
if curr_bound + curr_weight < final_res:
curr_path[level] = i
Dr. Pradeep K R & Dr. Vishwa Kiran S
BMSIT&M-Bengaluru-64
Page 20 of 42
Artificial Intelligence Laboratory 18AIL57
5 th Sem
Dept. Of AI & ML
visited[i] = True
# call TSPRec for the next level
TSPRec(adj, curr_bound, curr_weight,
level + 1, curr_path, visited)
# Else we have to prune the node by resetting
# all changes to curr_weight and curr_bound
curr_weight -= adj[curr_path[level - 1]][i]
curr_bound = temp
T&
M
-A
I&
# This function sets up final_path
def TSP(adj):
# Calculate initial lower bound for the root node
# using the formula 1/2 * (sum of first min +
# second min) for all edges. Also initialize the
# curr_path and visited array
curr_bound = 0
curr_path = [-1] * (N + 1)
visited = [False] * N
M
L
# Also reset the visited array
visited = [False] * len(visited)
for j in range(level):
if curr_path[j] != -1:
visited[curr_path[j]] = True
BM
SI
# Compute initial bound
for i in range(N):
curr_bound += (firstMin(adj, i) +
secondMin(adj, i))
# Rounding off the lower bound to an integer
curr_bound = math.ceil(curr_bound / 2)
# We start at vertex 1 so the first vertex
# in curr_path[] is 0
visited[0] = True
curr_path[0] = 0
# Call to TSPRec for curr_weight
# equal to 0 and level 1
TSPRec(adj, curr_bound, 0, 1, curr_path, visited)
# Driver code
# Adjacency matrix for the given graph
adj = [[0, 4, 12, 7],
[5, 0, 0, 18],
[11, 0, 0, 6],
[10, 2, 3, 0]]
Dr. Pradeep K R & Dr. Vishwa Kiran S
BMSIT&M-Bengaluru-64
Page 21 of 42
Artificial Intelligence Laboratory 18AIL57
5 th Sem
M
L
N=4
# final_path[] stores the final solution
# i.e. the // path of the salesman.
final_path = [None] * (N + 1)
# visited[] keeps track of the already
# visited nodes in a particular path
visited = [False] * N
# Stores the final minimum weight
# of shortest tour.
final_res = maxsize
TSP(adj)
print("Minimum cost :", final_res)
print("Path Taken : ", end = ' ')
for i in range(N + 1):
print(final_path[i], end = ' ')
Dept. Of AI & ML
BM
SI
T&
M
-A
I&
Output:
Minimum cost : 25
Path Taken : 0 2 3 1 0
Dr. Pradeep K R & Dr. Vishwa Kiran S
BMSIT&M-Bengaluru-64
Page 22 of 42
Artificial Intelligence Laboratory 18AIL57
5 th Sem
Dept. Of AI & ML
6.Implementation of the problem-solving strategies: either using Forward Chaining or
Backward Chaining.
M
I&
-A
BM
SI
# -----------------------------print('PART1. Data')
print(' 1)Rules')
for i in range(len(R)):
print(' R', i+1, ': ', end='')
for j in range(len(R[i])-1):
print(R[i][j], end= ' ')
print('->', R[i][-1])
T&
M
R=[]
for i in range(len(line)):
k=i+1
if line[i]=='1) Rules':
while line[k] != '2) Facts':
r = deque(line[k].split())
rhs = r.popleft()
r.append(rhs)
R.append(list(r))
k=k+1
elif line[i]=='2) Facts':
Fact=line[k].split()
elif line[i]=='3) Goal':
Goal=line[k]
L
#6:Implementation of the problem solving strategies: using Forward Chaining
from collections import deque
import copy
file=open(input('file:'))
line=file.readlines()
line=list(map(lambda s: s.strip(),line)) #A lambda function can take any number of arguments,
# but can only have one expression.
print()
print(' 2)Facts')
print(' ', end='')
for i in Fact:
print(i,' ',end='')
print();print()
print(' 3)Goal')
print(' ', Goal)
Dr. Pradeep K R & Dr. Vishwa Kiran S
BMSIT&M-Bengaluru-64
Page 23 of 42
Artificial Intelligence Laboratory 18AIL57
5 th Sem
Dept. Of AI & ML
# ------------------------------------Path=[]
Flag=[]
origin_fact = copy.deepcopy(Fact)
print('PART2. Trace')
T&
M
-A
I&
M
L
# Set initial value
count=0
Yes = False
while Goal not in Fact and Yes==False: #fact When the final element is added to or when it
doesn't work even after finishing it.
count += 1
print(' ', end='')
print('ITERATION',count)
K=-1
apply = False
while K<len(R)-1 and not apply: #until it finds one applicable rule.
K=K+1
print(' R', K + 1, ': ', end='')
for i, v in enumerate(R[K]): # Print Kth rule (R[K])
if i < len(R[K]) -1:
print(v, '', end='')
else:
print('->',v, end='')
BM
SI
if str(K+1) in Flag: #if there is a flag
b = Flag.index(str(K+1)) +1
if Flag[b]==[1]:
print(', skip, because flag1 raised')
elif Flag[b]==[2]:
print(', skip, because flag2 raised')
else: #no flag
for i, v in enumerate(R[K]): # Are all the left sides of the kth rule present?
if i == len(R[K]) -1:
continue
if v in Fact:
if R[K][-1] in Fact: # If the right-hand side already exists
print(' not applied, because RHS in facts. Raise flag2')
Flag.append(str(K + 1)); Flag.append([2])
break
elif v == R[K][-2]:
apply = True
P=K+1
Dr. Pradeep K R & Dr. Vishwa Kiran S
BMSIT&M-Bengaluru-64
Page 24 of 42
Artificial Intelligence Laboratory 18AIL57
5 th Sem
Dept. Of AI & ML
break
else:
print(', not applied, because of lacking ', v)
break
M
I&
-A
BM
SI
T&
M
print()
print('PART3. Results')
if Goal in origin_fact:
print(' ', end='')
print('Goal A in facts. Empty path.')
else:
if Goal in Fact:
print(' ',end='')
print('1) Goal',Goal,'achieved')
print(' ', end='')
print('2) Path:', end='')
for i in Path:
print('R', i, ' ', end='')
else:
print('1) Goal',Goal,' not achieved')
L
if apply:
Fact.append(R[P-1][-1])
Flag.append(str(P)); Flag.append([1])
Path.append(P)
print(', apply, Raise flag1. Facts ', end='')
for i in Fact:
print(i,' ', end='')
print()
elif K== len(R)-1:
Yes=True
## Input & Output
- Input: A text file that contains rules, fact and goal to deal with.
Example of Input - Testcase 1
```
Test 1. Initial fact in right hand side
1) Rules
LA
KL
AD
MD
ZFB
FCD
Dr. Pradeep K R & Dr. Vishwa Kiran S
BMSIT&M-Bengaluru-64
Page 25 of 42
Artificial Intelligence Laboratory 18AIL57
5 th Sem
Dept. Of AI & ML
DA
2) Facts
ABC
3) Goal
Z
- Output : Data, Trace and Results
Example of Output - Testcase 1
```
forwardChaining.py
file: test1.txt
M
I&
-A
BM
3)Goal
Z
T&
M
2)Facts
A B C
-> L
-> K
-> A
-> M
B -> Z
D -> F
-> D
SI
1)Rules
R1:A
R2:L
R3:D
R4:D
R5:F
R6:C
R7:A
L
PART1. Data
PART2. Trace
ITERATION 1
R 1 :A -> L, apply, Raise flag1. Facts A B C L
ITERATION 2
R 1 :A -> L, skip, because flag1 raised
R 2 :L -> K, apply, Raise flag1. Facts A B C L K
ITERATION 3
R 1 :A -> L, skip, because flag1 raised
R 2 :L -> K, skip, because flag1 raised
R 3 :D -> A, not applied, because of lacking D
R 4 :D -> M, not applied, because of lacking D
R 5 :F B -> Z, not applied, because of lacking F
R 6 :C D -> F, not applied, because of lacking D
R 7 :A -> D, apply, Raise flag1. Facts A B C L K D
ITERATION 4
Dr. Pradeep K R & Dr. Vishwa Kiran S
BMSIT&M-Bengaluru-64
Page 26 of 42
Artificial Intelligence Laboratory 18AIL57
5 th Sem
Dept. Of AI & ML
-A
BM
SI
```
T&
M
PART3. Results
1) Goal Z achieved
2) Path:R 1 R 2 R 7 R 4 R 6 R 5
Process finished with exit code 0
I&
M
L
R 1 :A -> L, skip, because flag1 raised
R 2 :L -> K, skip, because flag1 raised
R 3 :D -> A not applied, because RHS in facts. Raise flag2
R 4 :D -> M, apply, Raise flag1. Facts A B C L K D M
ITERATION 5
R 1 :A -> L, skip, because flag1 raised
R 2 :L -> K, skip, because flag1 raised
R 3 :D -> A, skip, because flag2 raised
R 4 :D -> M, skip, because flag1 raised
R 5 :F B -> Z, not applied, because of lacking F
R 6 :C D -> F, apply, Raise flag1. Facts A B C L K D M F
ITERATION 6
R 1 :A -> L, skip, because flag1 raised
R 2 :L -> K, skip, because flag1 raised
R 3 :D -> A, skip, because flag2 raised
R 4 :D -> M, skip, because flag1 raised
R 5 :F B -> Z, apply, Raise flag1. Facts A B C L K D M F Z
Dr. Pradeep K R & Dr. Vishwa Kiran S
BMSIT&M-Bengaluru-64
Page 27 of 42
Artificial Intelligence Laboratory 18AIL57
5 th Sem
Dept. Of AI & ML
7.Implement resolution principle on FOPL related problems
#7: Implement resolution principle on FOPL related problems
import time
start_time = time.time()
import re
import itertools
import collections
import copy
import queue
-A
T&
M
n=int(data1[0])
queries=list()
for i in range(1,n+1):
queries.append(data1[i].rstrip())
k=int(data1[n+1])
kbbefore=list()
I&
M
L
p=open("input4.txt","r")
data=list()
data1= p.readlines()
count=0
BM
SI
def CNF(sentence):
temp=re.split("=>",sentence)
temp1=temp[0].split('&')
for i in range(0,len(temp1)):
if temp1[i][0]=='~':
temp1[i]=temp1[i][1:]
else:
temp1[i]='~'+temp1[i]
temp2='|'.join(temp1)
temp2=temp2+'|'+temp[1]
return temp2
variableArray = list("abcdefghijklmnopqrstuvwxyz")
variableArray2 = [ ]
variableArray3 = [ ]
variableArray5 = [ ]
variableArray6 = [ ]
for eachCombination in itertools.permutations(variableArray, 2):
variableArray2.append(eachCombination[0] + eachCombination[1])
Dr. Pradeep K R & Dr. Vishwa Kiran S
BMSIT&M-Bengaluru-64
Page 28 of 42
Artificial Intelligence Laboratory 18AIL57
5 th Sem
Dept. Of AI & ML
for eachCombination in itertools.permutations(variableArray, 3):
variableArray3.append(eachCombination[0] + eachCombination[1] + eachCombination[2])
for eachCombination in itertools.permutations(variableArray, 4):
variableArray5.append(eachCombination[0] + eachCombination[1] + eachCombination[2]+
eachCombination[3])
for eachCombination in itertools.permutations(variableArray, 5):
variableArray6.append(eachCombination[0] + eachCombination[1] + eachCombination[2] +
eachCombination[3] + eachCombination[4])
variableArray = variableArray + variableArray2 + variableArray3 + variableArray5 +
variableArray6
capitalVariables = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
number=0
BM
SI
T&
M
-A
I&
M
L
def standardizationnew(sentence):
newsentence=list(sentence)
i=0
global number
variables=collections.OrderedDict()
positionsofvariable=collections.OrderedDict()
lengthofsentence=len(sentence)
for i in range(0,lengthofsentence-1):
if(newsentence[i]==',' or newsentence[i]=='('):
if newsentence[i+1] not in capitalVariables:
substitution=variables.get(newsentence[i+1])
positionsofvariable[i+1]=i+1
if not substitution :
variables[newsentence[i+1]]=variableArray[number]
newsentence[i+1]=variableArray[number]
number+=1
else:
newsentence[i+1]=substitution
return "".join(newsentence)
def insidestandardizationnew(sentence):
lengthofsentence=len(sentence)
newsentence=sentence
variables=collections.OrderedDict()
positionsofvariable=collections.OrderedDict()
global number
i=0
while i <=len(newsentence)-1 :
if(newsentence[i]==',' or newsentence[i]=='('):
if newsentence[i+1] not in capitalVariables:
j=i+1
while(newsentence[j]!=',' and newsentence[j]!=')' ):
j+=1
Dr. Pradeep K R & Dr. Vishwa Kiran S
BMSIT&M-Bengaluru-64
Page 29 of 42
Artificial Intelligence Laboratory 18AIL57
5 th Sem
Dept. Of AI & ML
substitution=variables.get(newsentence[i+1:j])
if not substitution :
variables[newsentence[i+1:j]]=variableArray[number]
newsentence=newsentence[:i+1]+variableArray[number]+newsentence[j:]
i=i+len(variableArray[number])
number+=1
else:
newsentence=newsentence[:i+1]+substitution+newsentence[j:]
i=i+len(substitution)
i+=1
return newsentence
BM
SI
T&
M
-A
I&
M
L
def replace(sentence,theta):
lengthofsentence=len(sentence)
newsentence=sentence
i=0
while i <=len(newsentence)-1 :
if(newsentence[i]==',' or newsentence[i]=='('):
if newsentence[i+1] not in capitalVariables:# This operator is used to check whether an
element is not present in the passed list or not
j=i+1
while(newsentence[j]!=',' and newsentence[j]!=')' ):
j+=1
nstemp=newsentence[i+1:j]
substitution=theta.get(nstemp)
if substitution :
newsentence=newsentence[:i+1]+substitution+newsentence[j:]
i=i+len(substitution)
i+=1
return newsentence
repeatedsentencecheck=collections.OrderedDict()
def insidekbcheck(sentence):
lengthofsentence=len(sentence)
newsentence=pattern.split(sentence)
newsentence.sort()
newsentence="|".join(newsentence)
global repeatedsentencecheck
i=0
while i <=len(newsentence)-1 :
if(newsentence[i]==',' or newsentence[i]=='('):
if newsentence[i+1] not in capitalVariables:
j=i+1
while(newsentence[j]!=',' and newsentence[j]!=')' ):
j+=1
Dr. Pradeep K R & Dr. Vishwa Kiran S
BMSIT&M-Bengaluru-64
Page 30 of 42
Artificial Intelligence Laboratory 18AIL57
5 th Sem
Dept. Of AI & ML
newsentence=newsentence[:i+1]+'x'+newsentence[j:]
i+=1
repeatflag=repeatedsentencecheck.get(newsentence)
if repeatflag :
return True
repeatedsentencecheck[newsentence]=1
return False
I&
M
L
for i in range(n+2,n+2+k):
data1[i]=data1[i].replace(" ","")
if "=>" in data1[i]:
data1[i]=data1[i].replace(" ","")
sentencetemp=CNF(data1[i].rstrip())
kbbefore.append(sentencetemp)
else:
kbbefore.append(data1[i].rstrip())
for i in range(0,k):
kbbefore[i]=kbbefore[i].replace(" ","")
BM
SI
T&
M
-A
kb={}
pattern=re.compile("\||&|=>") #we can remove the '\|'' to speed up as 'OR' doesnt come in the KB
pattern1=re.compile("[(,]")
for i in range(0,k):
kbbefore[i]=standardizationnew(kbbefore[i])
temp=pattern.split(kbbefore[i])
lenoftemp=len(temp)
for j in range(0,lenoftemp):
clause=temp[j]
clause=clause[:-1]
predicate=pattern1.split(clause)
argumentlist=predicate[1:]
lengthofpredicate=len(predicate)-1
if predicate[0] in kb:
if lengthofpredicate in kb[predicate[0]]:
kb[predicate[0]][lengthofpredicate].append([kbbefore[i],temp,j,predicate[1:]])
else:
kb[predicate[0]][lengthofpredicate]=[kbbefore[i],temp,j,predicate[1:]]
else:
kb[predicate[0]]={lengthofpredicate:[[kbbefore[i],temp,j,predicate[1:]]]}
for qi in range(0,n):
queries[qi]=standardizationnew(queries[qi])
def substituevalue(paramArray, x, y):
for index, eachVal in enumerate(paramArray):
if eachVal == x:
Dr. Pradeep K R & Dr. Vishwa Kiran S
BMSIT&M-Bengaluru-64
Page 31 of 42
Artificial Intelligence Laboratory 18AIL57
5 th Sem
Dept. Of AI & ML
paramArray[index] = y
return paramArray
BM
SI
T&
M
-A
I&
M
L
def unificiation(arglist1,arglist2):
theta = collections.OrderedDict()
for i in range(len(arglist1)):
if arglist1[i] != arglist2[i] and (arglist1[i][0] in capitalVariables) and (arglist2[i][0] in
capitalVariables):
return []
elif arglist1[i] == arglist2[i] and (arglist1[i][0] in capitalVariables) and (arglist2[i][0] in
capitalVariables):
if arglist1[i] not in theta.keys():
theta[arglist1[i]] = arglist2[i]
elif (arglist1[i][0] in capitalVariables) and not (arglist2[i][0] in capitalVariables):
if arglist2[i] not in theta.keys():
theta[arglist2[i]] = arglist1[i]
arglist2 = substituevalue(arglist2, arglist2[i], arglist1[i])
elif not (arglist1[i][0] in capitalVariables) and (arglist2[i][0] in capitalVariables):
if arglist1[i] not in theta.keys():
theta[arglist1[i]] = arglist2[i]
arglist1 = substituevalue(arglist1, arglist1[i], arglist2[i])
elif not (arglist1[i][0] in capitalVariables) and not (arglist2[i][0] in capitalVariables):
if arglist1[i] not in theta.keys():
theta[arglist1[i]] = arglist2[i]
arglist1 = substituevalue(arglist1, arglist1[i], arglist2[i])
else:
argval=theta[arglist1[i]]
theta[arglist2[i]]=argval
arglist2 = substituevalue(arglist2, arglist2[i], argval)
return [arglist1,arglist2,theta]
def resolution():
global repeatedsentencecheck
answer=list()
qrno=0
for qr in queries:
qrno+=1
repeatedsentencecheck.clear()
q=queue.Queue()
query_start=time.time()
kbquery=copy.deepcopy(kb)
ans=qr
if qr[0]=='~':
ans=qr[1:]
else:
ans='~'+qr
Dr. Pradeep K R & Dr. Vishwa Kiran S
BMSIT&M-Bengaluru-64
Page 32 of 42
Artificial Intelligence Laboratory 18AIL57
5 th Sem
Dept. Of AI & ML
BM
SI
T&
M
-A
I&
M
L
q.put(ans)
label:outerloop
currentanswer="FALSE"
counter=0
while True:
counter+=1
if q.empty():
break
ans=q.get()
label:outerloop1
ansclauses=pattern.split(ans)
lenansclauses=len(ansclauses)
flagmatchedwithkb=0
innermostflag=0
for ac in range(0,lenansclauses):
insidekbflag=0
ansclausestruncated=ansclauses[ac][:-1]
ansclausespredicate=pattern1.split(ansclausestruncated)
lenansclausespredicate=len(ansclausespredicate)-1
if ansclausespredicate[0][0]=='~':
anspredicatenegated=ansclausespredicate[0][1:]
else:
anspredicatenegated="~"+ansclausespredicate[0]
x=kbquery.get(anspredicatenegated,{}).get(lenansclausespredicate)
if not x:
continue
else:
lenofx=len(x)
for numofpred in range(0,lenofx):
insidekbflag=0
putinsideq=0
sentenceselected=x[numofpred]
thetalist=unificiation(copy.deepcopy(sentenceselected[3]),copy.deepcopy(ansclausespredicate[1:
]))
if(len(thetalist)!=0):
for key in thetalist[2]:
tl=thetalist[2][key]
tl2=thetalist[2].get(tl)
if tl2:
thetalist[2][key]=tl2
flagmatchedwithkb=1
notincludedindex=sentenceselected[2]
senclause=copy.deepcopy(sentenceselected[1])
mergepart1=""
del senclause[notincludedindex]
Dr. Pradeep K R & Dr. Vishwa Kiran S
BMSIT&M-Bengaluru-64
Page 33 of 42
Artificial Intelligence Laboratory 18AIL57
5 th Sem
Dept. Of AI & ML
SI
T&
M
-A
I&
M
L
ansclauseleft=copy.deepcopy(ansclauses)
del ansclauseleft[ac]
for am in range(0,len(senclause)):
senclause[am]=replace(senclause[am],thetalist[2])
mergepart1=mergepart1+senclause[am]+'|'
for remain in range(0,len(ansclauseleft)):
listansclauseleft=ansclauseleft[remain]
ansclauseleft[remain]=replace(listansclauseleft,thetalist[2])
if ansclauseleft[remain] not in senclause:
mergepart1=mergepart1+ansclauseleft[remain]+'|'
mergepart1=mergepart1[:-1]
if mergepart1=="":
currentanswer="TRUE"
break
ckbflag=insidekbcheck(mergepart1)
if not ckbflag:
mergepart1=insidestandardizationnew(mergepart1)
ans=mergepart1
temp=pattern.split(ans)
lenoftemp=len(temp)
for j in range(0,lenoftemp):
clause=temp[j]
clause=clause[:-1]
predicate=pattern1.split(clause)
argumentlist=predicate[1:]
lengthofpredicate=len(predicate)-1
if predicate[0] in kbquery:
if lengthofpredicate in kbquery[predicate[0]]:
BM
kbquery[predicate[0]][lengthofpredicate].append([mergepart1,temp,j,argumentlist])
else:
kbquery[predicate[0]][lengthofpredicate]=[[mergepart1,temp,j,argumentlist]]
else:
kbquery[predicate[0]]={lengthofpredicate:[[mergepart1,temp,j,argumentlist]]}
q.put(ans)
if(currentanswer=="TRUE"):
break
if(currentanswer=="TRUE"):
break
if(counter==2000 or (time.time()-query_start)>20):
break
answer.append(currentanswer)
return answer
Dr. Pradeep K R & Dr. Vishwa Kiran S
BMSIT&M-Bengaluru-64
Page 34 of 42
Artificial Intelligence Laboratory 18AIL57
5 th Sem
Dept. Of AI & ML
M
I&
T&
M
BM
SI
Input2.txt
6
F(Bob)
H(John)
~H(Alice)
~H(John)
G(Bob)
G(Tom)
14
A(x) => H(x)
D(x,y) => ~H(y)
B(x,y) & C(x,y) => A(x)
B(John,Alice)
B(John,Bob)
D(x,y) & Q(y) => C(x,y)
D(John,Alice)
Q(Bob)
D(John,Bob)
F(x) => G(x)
G(x) => H(x)
H(x) => F(x)
R(x) => H(x)
R(Tom)
-A
input1.txt
1
Ancestor(Liz,Bob)
6
Mother(Liz,Charley)
Father(Charley,Billy)
~Mother(x,y) | Parent(x,y)
~Father(x,y) | Parent(x,y)
~Parent(x,y) | Ancestor(x,y)
Parent(x,y) & Ancestor(y,z) => Ancestor(x,z)
L
if __name__ == '__main__':
finalanswer=resolution()
o=open("output.txt","w+")
wc=0
while(wc < n-1):
o.write(finalanswer[wc]+"\n")
wc+=1
o.write(finalanswer[wc])
o.close()
Output.txt TRUE
Dr. Pradeep K R & Dr. Vishwa Kiran S
BMSIT&M-Bengaluru-64
Page 35 of 42
Artificial Intelligence Laboratory 18AIL57
5 th Sem
Dept. Of AI & ML
8.Implement any Game and demonstrate the Game playing strategies
#8:Implement any Game and demonstrate the Game playing strategies.
#Implementation of Two Player Tic-Tac-Toe game in Python.
''' We will make the board using dictionary
in which keys will be the location(i.e : top-left,mid-right,etc.)
and initialliy it's values will be empty space and then after every move
we will change the value according to player's choice of move. '''
L
theBoard = {'7': ' ' , '8': ' ' , '9': ' ' ,
'4': ' ' , '5': ' ' , '6': ' ' ,
'1': ' ' , '2': ' ' , '3': ' ' }
M
board_keys = []
I&
for key in theBoard:
board_keys.append(key)
T&
M
-A
''' We will have to print the updated board after every move in the game and
thus we will make a function in which we'll define the printBoard function
so that we can easily print the board everytime by calling this function. '''
BM
SI
def printBoard(board):
print(board['7'] + '|' + board['8'] + '|' + board['9'])
print('-+-+-')
print(board['4'] + '|' + board['5'] + '|' + board['6'])
print('-+-+-')
print(board['1'] + '|' + board['2'] + '|' + board['3'])
# Now we'll write the main function which has all the gameplay functionality.
def game():
turn = 'X'
count = 0
for i in range(10):
printBoard(theBoard)
print("It's your turn," + turn + ".Move to which place?")
move = input()
if theBoard[move] == ' ':
theBoard[move] = turn
count += 1
Dr. Pradeep K R & Dr. Vishwa Kiran S
BMSIT&M-Bengaluru-64
Page 36 of 42
Artificial Intelligence Laboratory 18AIL57
5 th Sem
Dept. Of AI & ML
else:
print("That place is already filled.\nMove to which place?")
continue
BM
SI
T&
M
-A
I&
M
L
# Now we will check if player X or O has won,for every move after 5 moves.
if count >= 5:
if theBoard['7'] == theBoard['8'] == theBoard['9'] != ' ': # across the top
printBoard(theBoard)
print("\nGame Over.\n")
print(" **** " +turn + " won. ****")
break
elif theBoard['4'] == theBoard['5'] == theBoard['6'] != ' ': # across the middle
printBoard(theBoard)
print("\nGame Over.\n")
print(" **** " +turn + " won. ****")
break
elif theBoard['1'] == theBoard['2'] == theBoard['3'] != ' ': # across the bottom
printBoard(theBoard)
print("\nGame Over.\n")
print(" **** " +turn + " won. ****")
break
elif theBoard['1'] == theBoard['4'] == theBoard['7'] != ' ': # down the left side
printBoard(theBoard)
print("\nGame Over.\n")
print(" **** " +turn + " won. ****")
break
elif theBoard['2'] == theBoard['5'] == theBoard['8'] != ' ': # down the middle
printBoard(theBoard)
print("\nGame Over.\n")
print(" **** " +turn + " won. ****")
break
elif theBoard['3'] == theBoard['6'] == theBoard['9'] != ' ': # down the right side
printBoard(theBoard)
print("\nGame Over.\n")
print(" **** " +turn + " won. ****")
break
elif theBoard['7'] == theBoard['5'] == theBoard['3'] != ' ': # diagonal
printBoard(theBoard)
print("\nGame Over.\n")
print(" **** " +turn + " won. ****")
break
elif theBoard['1'] == theBoard['5'] == theBoard['9'] != ' ': # diagonal
printBoard(theBoard)
print("\nGame Over.\n")
print(" **** " +turn + " won. ****")
break
Dr. Pradeep K R & Dr. Vishwa Kiran S
BMSIT&M-Bengaluru-64
Page 37 of 42
Artificial Intelligence Laboratory 18AIL57
5 th Sem
Dept. Of AI & ML
# If neither X nor O wins and the board is full, we'll declare the result as 'tie'.
if count == 9:
print("\nGame Over.\n")
print("It's a Tie!!")
I&
M
# Now we will ask if player wants to restart the game or not.
restart = input("Do want to play Again?(y/n)")
if restart == "y" or restart == "Y":
for key in board_keys:
theBoard[key] = " "
L
# Now we have to change the player after every move.
if turn =='X':
turn = 'O'
else:
turn = 'X'
game()
T&
M
-A
if __name__ == "__main__":
game()
BM
SI
Output:
||
-+-+||
-+-+||
It's your turn,X.Move to which place?
4
||
-+-+X| |
-+-+||
It's your turn,O.Move to which place?
3
||
-+-+X| |
-+-+-
Dr. Pradeep K R & Dr. Vishwa Kiran S
BMSIT&M-Bengaluru-64
Page 38 of 42
Artificial Intelligence Laboratory 18AIL57
5 th Sem
Dept. Of AI & ML
| |O
It's your turn,X.Move to which place?
2
||
-+-+X| |
-+-+|X|O
It's your turn,O.Move to which place?
Game Over.
M
I&
-A
SI
BM
7
O| |
-+-+X|O|X
-+-+|X|O
T&
M
6
||
-+-+X|O|X
-+-+|X|O
It's your turn,O.Move to which place?
L
5
||
-+-+X|O|
-+-+|X|O
It's your turn,X.Move to which place?
**** O won. ****
Do want to play Again?(y/n)
Dr. Pradeep K R & Dr. Vishwa Kiran S
BMSIT&M-Bengaluru-64
Page 39 of 42
Artificial Intelligence Laboratory 18AIL57
5 th Sem
Dept. Of AI & ML
Viva Questions
BM
SI
T&
M
-A
I&
M
L
1) What is Artificial Intelligence?
Artificial Intelligence is an area of computer science that emphasizes the creation of intelligent machine that work and
reacts like humans.
2) What is an artificial intelligence Neural Networks?
Artificial intelligence Neural Networks can model mathematically the way biological brain works, allowing the
machine to think and learn the same way the humans do- making them capable of recognizing things like speech,
objects and animals like we do.
3) What are the various areas where AI (Artificial Intelligence) can be used?
Artificial Intelligence can be used in many areas like Computing, Speech recognition, Bio-informatics, Humanoid
robot, Computer software, Space and Aeronautics’s etc.
4) Which is not commonly used programming language for AI?
Perl language is not commonly used programming language for AI
5) What is Prolog in AI?
In AI, Prolog is a programming language based on logic.
6) Give an explanation on the difference between strong AI and weak AI?
Strong AI makes strong claims that computers can be made to think on a level equal to humans while weak AI simply
predicts that some features that are resembling to human intelligence can be incorporated to computer to make it more
useful tools.
7) Mention the difference between statistical AI and Classical AI ?
Statistical AI is more concerned with “inductive” thought like given a set of pattern, induce the trend etc. While,
classical AI, on the other hand, is more concerned with “ deductive” thought given as a set of constraints, deduce a
conclusion etc.
8) What is alternate, artificial, compound and natural key?
Alternate Key: Excluding primary keys all candidate keys are known as Alternate Keys.
Artificial Key: If no obvious key either stands alone or compound is available, then the last resort is to, simply create
a key, by assigning a number to each record or occurrence. This is known as artificial key.
Compound Key: When there is no single data element that uniquely defines the occurrence within a construct, then
integrating multiple elements to create a unique identifier for the construct is known as Compound Key.
Natural Key: Natural key is one of the data element that is stored within a construct, and which is utilized as the
primary key.
9) What does a production rule consist of?
The production rule comprises of a set of rule and a sequence of steps.
10) Which search method takes less memory?
The “depth first search” method takes less memory.
11) Which is the best way to go for Game playing problem?
Heuristic approach is the best way to go for game playing problem, as it will use the technique based on intelligent
guesswork. For example, Chess between humans and computers as it will use brute force computation, looking at
hundreds of thousands of positions.
12) A* algorithm is based on which search method?
A* algorithm is based on best first search method, as it gives an idea of optimization and quick choose of path, and
all characteristics lie in A* algorithm.
13) What does a hybrid Bayesian network contain?
A hybrid Bayesian network contains both a discrete and continuous variables.
14) What is agent in artificial intelligence?
Anything perceives its environment by sensors and acts upon an environment by effectors are known as Agent. Agent
includes Robots, Programs, and Humans etc.
15) What does Partial order or planning involve?
In partial order planning , rather than searching over possible situation it involves searching over the space of possible
plans. The idea is to construct a plan piece by piece.
16) What are the two different kinds of steps that we can take in constructing a plan?
a)
Add an operator (action)
b)
Add an ordering constraint between operators
17) Which property is considered as not a desirable property of a logical rule-based system?
Dr. Pradeep K R & Dr. Vishwa Kiran S
BMSIT&M-Bengaluru-64
Page 40 of 42
Artificial Intelligence Laboratory 18AIL57
5 th Sem
Dept. Of AI & ML
BM
SI
T&
M
-A
I&
M
L
“Attachment” is considered as not a desirable property of a logical rule based system.
18) What is Neural Network in Artificial Intelligence?
In artificial intelligence, neural network is an emulation of a biological neural system, which receives the data, process
the data and gives the output based on the algorithm and empirical data.
19) When an algorithm is considered completed?
An algorithm is said completed when it terminates with a solution when one exists.
20) What is a heuristic function?
A heuristic function ranks alternatives, in search algorithms, at each branching step based on the available information
to decide which branch to follow.
21) What is the function of the third component of the planning system?
In a planning system, the function of the third component is to detect when a solution to problem has been found.
22) What is “Generality” in AI ?
Generality is the measure of ease with which the method can be adapted to different domains of application.
23) What is a top-down parser?
A top-down parser begins by hypothesizing a sentence and successively predicting lower level constituents until
individual pre-terminal symbols are written.
24) Mention the difference between breadth first search and best first search in artificial intelligence?
These are the two strategies which are quite similar. In best first search, we expand the nodes in accordance with the
evaluation function. While, in breadth first search a node is expanded in accordance to the cost function of the parent
node.
25) What are frames and scripts in “Artificial Intelligence”?
Frames are a variant of semantic networks which is one of the popular ways of presenting non-procedural knowledge
in an expert system. A frame which is an artificial data structure is used to divide knowledge into substructure by
representing “stereotyped situations’. Scripts are similar to frames, except the values that fill the slots must be
ordered. Scripts are used in natural language understanding systems to organize a knowledge base in terms of the
situation that the system should understand.
26) What is FOPL stands for and explain its role in Artificial Intelligence?
FOPL stands for First Order Predicate Logic, Predicate Logic provides
a)
A language to express assertions about certain “World”
b)
An inference system to deductive apparatus whereby we may draw conclusions from such assertion
c)
A semantic based on set theory
27) What does the language of FOPL consists of
a)
A set of constant symbols
b)
A set of variables
c)
A set of predicate symbols
d)
A set of function symbols
e)
The logical connective
f)
The Universal Quantifier and Existential Qualifier
g)
A special binary relation of equality
28) For online search in ‘Artificial Intelligence’ which search agent operates by interleaving computation and
action?
In online search, it will first take action and then observes the environment.
29) Which search algorithm will use a limited amount of memory in online search?
RBFE and SMA* will solve any kind of problem that A* can’t by using a limited amount of memory.
30) In ‘Artificial Intelligence’ where you can use the Bayes rule?
In Artificial Intelligence to answer the probabilistic queries conditioned on one piece of evidence, Bayes rule can be
used.
31) For building a Bayes model how many terms are required?
For building a Bayes model in AI, three terms are required; they are one conditional probability and two unconditional
probability.
32) While creating Bayesian Network what is the consequence between a node and its predecessors?
While creating Bayesian Network, the consequence between a node and its predecessors is that a node can be
conditionally independent of its predecessors.
33) To answer any query how the Bayesian network can be used?
If a Bayesian Network is a representative of the joint distribution, then by summing all the relevant joint entries, it can
solve any query.
Dr. Pradeep K R & Dr. Vishwa Kiran S
BMSIT&M-Bengaluru-64
Page 41 of 42
Artificial Intelligence Laboratory 18AIL57
5 th Sem
Dept. Of AI & ML
BM
SI
T&
M
-A
I&
M
L
34) What combines inductive methods with the power of first order representations?
Inductive logic programming combines inductive methods with the power of first order representations.
35) In Inductive Logic Programming what needed to be satisfied?
The objective of an Inductive Logic Programming is to come up with a set of sentences for the hypothesis such that
the entailment constraint is satisfied.
36) In top-down inductive learning methods how many literals are available? What are they?
There are three literals available in top-down inductive learning methods they are
a)
Predicates
b)
Equality and Inequality
c)
Arithmetic Literals
37) Which algorithm inverts a complete resolution strategy?
‘Inverse Resolution’ inverts a complete resolution, as it is a complete algorithm for learning first order theories.
38) In speech recognition what kind of signal is used?
In speech recognition, Acoustic signal is used to identify a sequence of words.
39) In speech recognition which model gives the probability of each word following each word?
Biagram model gives the probability of each word following each other word in speech recognition.
40) Which algorithm is used for solving temporal probabilistic reasoning?
To solve temporal probabilistic reasoning, HMM (Hidden Markov Model) is used, independent of transition and
sensor model.
41) What is Hidden Markov Model (HMMs) is used?
Hidden Markov Models are a ubiquitous tool for modelling time series data or to model sequence behaviour. They
are used in almost all current speech recognition systems.
42) In Hidden Markov Model, how does the state of the process is described?
The state of the process in HMM’s model is described by a ‘Single Discrete Random Variable’.
43) In HMM’s, what are the possible values of the variable?
‘Possible States of the World’ is the possible values of the variable in HMM’s.
44) In HMM, where does the additional variable is added?
While staying within the HMM network, the additional state variables can be added to a temporal model.
45) In Artificial Intelligence, what do semantic analyses used for?
In Artificial Intelligence, to extract the meaning from the group of sentences semantic analysis is used.
46) What is meant by compositional semantics?
The process of determining the meaning of P*Q from P,Q and* is known as Compositional Semantics.
47) How logical inference can be solved in Propositional Logic?
In Propositional Logic, Logical Inference algorithm can be solved by using
a)
Logical Equivalence
b)
Validity
c)
Satisfying ability
48) Which process makes different logical expression looks identical?
‘Unification’ process makes different logical expressions identical. Lifted inferences require finding substitute which
can make a different expression looks identical. This process is called unification.
49) Which algorithm in ‘Unification and Lifting’ takes two sentences and returns a unifier?
In ‘Unification and Lifting’ the algorithm that takes two sentences and returns a unifier is ‘Unify’ algorithm.
50) Which is the most straight forward approach for planning algorithm?
State space search is the most straight forward approach for planning algorithm because it takes account of everything
for finding a solution.
Dr. Pradeep K R & Dr. Vishwa Kiran S
BMSIT&M-Bengaluru-64
Page 42 of 42
Download