AI Lab Manual
AI Lab Manual
LABORATORY MANUAL
Artificial Intelligence [BAD402]
t Related Image
USN:
Branch/Semester:
Academic Year:
Sri Raghavendra Educational Institutions Society(R)
GENERAL INSTRUCTIONS
Do’s
1. Do wear ID card and follow dress code.
2. Do log off the computers when you finish.
3. Do ask the staff for assistance if you need help.
4. Do keep your voice low when speaking to others in the LAB.
5. Do ask for assistance in downloading any software.
6. Do make suggestions as to how we can improve the LAB.
7. In case of any hardware related problem, ask LAB in charge for solution.
8. If you are the last one leaving the LAB, make sure that the staff in charge of the LAB is informed
to close the LAB.
9. Be on time to LAB sessions.
10. Do keep the LAB as clean as possible.
Don’ts
1. Do not use mobile phone inside the lab.
2. Don’t do anything that can make the LAB dirty (like eating, throwing waste papers etc.).
3. Do not carry any external devices without permission.
5. Don’t interchange any part of one computer with another.
6. Don’t leave the computers of the LAB turned on while leaving the LAB.
7. Do not install or download any software or modify or delete any system files on any lab
computers.
8. Do not damage, remove, or disconnect any labels, parts, cables, or equipment.
LIST OF EXPERIMENTS
SL.
EXPERIMENTS
NO
1 Implement and Demonstrate Depth First Search Algorithm on Water Jug Problem.
Implementation of the problem solving strategies: either using Forward Chaining or Backward
7
Chaining.
10 Build a bot which provides all the information related to text in search box.
Vision
To bring forth technically versatile, Research oriented,
Industry ready engineers in the field of Artificial
Intelligence and Machine Learning.
Mission
1. Facilitate modern infrastructure and versatile learning resources to
produce self-sustainable professionals.
2. Facilitate project based learning and skill upgradation through
industry collaborations.
3. Inculcate professional ethics, leadership qualities and practice
lifelong learning.
Sri Raghavendra Educational Institutions Society(R)
Different people think of Al differently and there is no unique definition. Various authors have
defined Al differently as given below.
• AI is the study of mental faculties through the use computational models
(Charniak and McDermott, 1985).
• The art of creating machines that perform functions which require intelligence
when performed by people (Kurzweil, 1990).
• AI is the study of the computations that make it possible to perceive, reason, and
act (Winston, 1992).
Applications
AI finds applications in almost all areas of real-life applications. Broadly speaking, business,
engineering, medicine, education and manufacturing are the main areas.
• Business: financial strategies, give advice
Sri Raghavendra Educational Institutions Society(R)
• Education: in teaching
• Fraud detection
• Object identification
• Information retrieval
Problem statement: We have two jugs, a 5-gallon (5-g) and the other 3-gallon (3-g) with no
measuring marker on them. There is endless supply of water through tap. Our task is to get 4
gallon of water in the 5-g jug. Solution: State space for this problem can be described as the set of
ordered pairs of integers (X, Y) such that X represents the number of gallons of water in 5-g jug
and Y for 3-g jug.
1. Start state is (0,0)
2. 2. Goal state is (4, N) for any value of NS3.
The possible operations that can be used in this problem are listed as follows:
• Fill 5-g jug from the tap and empty the 5-g jug by throwing water down the drain
• Fill 3-g jug from the tap and empty the 3-g jug by throwing water down the drain
• Pour some or 3-g water from 5-g jug into the 3-g jug to make it full
• Pour some or full 3-g jug water into the 5-g jug
These operations can formally be defined as production rules as given in table.
Rule
Left of rule Right of rule Description
No
(X, Y | X + Y ≤ 5 ^ Y >
5 (X + Y, 0) Empty 3-g into 5-g jug
0)
Sri Raghavendra Educational Institutions Society(R)
(X, Y | X + Y ≤ 3 ^ X >
6 (0, X + Y) Empty 5-g into 3-g jug
0)
(5, Y – (5 – X))
(X, Y | X + Y ≥ 5 ^ Y > Pour water from 3-g jug into 5-g
7 until 5-g jug is
0) jug
full
(X, Y | X + Y ≥ 3 ^ X > Pour water from 5-g jug into 3-g jug
8 (X – (3 – Y), 3)
0) until 3-g jug is full
Depth-First Search
In the depth-first search (DFS), we go as far down as possible into the search tree/graph before
backing up and trying alternatives. It works by always generating a descendent of the most
recently expanded node until some depth cut off is reached and then backtracks to next most
recently expanded node and generates one of its descendants.
We can implement DFS by using two lists called OPEN and CLOSED. The OPEN list contains
those states that are to be expanded, and CLOSED list keeps track of states already expanded
Here OPEN and CLOSED lists are maintained as stacks.
Missionaries and Cannibals Problem:
Problem statement: Three missionaries and three cannibals want to cross a river. There is a boat
on their side of the river that can be used by either one or two persons. How should they use this
boat to cross the river in such a way that cannibals never outnumber missionaries on either side
of the river? If the cannibals ever outnumber the missionaries (on either bank) then the
missionaries will be eaten. How can they all cross over without anyone being eaten?
Solution: State space for this problem can be described as the set of ordered pairs of left and right
banks of the river as (L, R) where each bank is represented as a list [nM, mC, B). Here n is the
number of missionaries M, m is the number of cannibals C, and B represents the boat.
Let us consider another problem of ‘Missionaries and Cannibals’ and see how we can we solve
this using production system.
Sri Raghavendra Educational Institutions Society(R)
1. Start state: ([3M, 3C, 1B], [OM, OC, OB]), 1B means that beat is present and OB means
it is absent.
2. Any state: {{n, M, mc, _), n2M, mC, _]), with constraints/conditions at any state as nj
(#0) Zm; n2 (+0) 2 m2; n, + n2 = 3, m + m2 = 3; boat can be either side.
It should be noted that by no means, this representation is unique. In fact, one may have number
of representations for the same problem. Table consists of production rules based on the chosen
representation. States on the left or right sides of river should be valid states satisfying the
constraints given in (2) above.
Breadth-First Search
The breadth-first search (BFS) expands all the states one step away from the start state, and then
expands all states two steps from start state, then three steps, etc., until a goal state is reached. All
successor states are examined at the same depth before going deeper. The BFS always gives an
optimal path or solution.
Sri Raghavendra Educational Institutions Society(R)
This search is implemented using two lists called OPEN and CLOSED. The OPEN list contains
those states that are to be expanded and CLOSED list keeps track of states already expanded. Here
OPEN list is maintained as a queue and CLOSED list as a stack.
Predicate Logic
The predicate logic is a logical extension of propositional logic, which deals with the validity,
satisfiability, and unsatisfiability (inconsistency) of a formula along with the inference rules for
derivation of a new formula. Predicate calculus is the study of predicate systems; when inference
rules are added to predicate calculus, it becomes predicate logic.
First-Order Predicate Calculus
If the quantification in predicate formula is only on simple variables and not on predicates or
functions then it is called first-order predicate calculus.
On the other hand, if the quantification is over first-order predicates and functions, then it
becomes second-order predicate calculus.
The first-order predicate calculus is a formal language in which a wide variety of statements are
expressed. The formulae in predicate calculus are formed using rules similar to those used in
propositional calculus.
When inference rules are added to first-order predicate calculus, it becomes first-order predicate
logic (FOL). Using inference rules, one can derive new formulae from the existing ones.
More Secure: These spreadsheets can be password secured in a laptop or personal computer
and the probability of losing them is way lesser in comparison to data written in registers or
piece of paper.
Data at One Place: Earlier, data was to be kept in different files and registers when the
paperwork was done. Now, this has become convenient as more than one worksheet can be
added in a single MS Excel file.
Neater and Clearer Visibility of Information: When the data is saved in the form of a table,
analysing becomes easier. Thus, information in a spreadsheet is more readable and
understandable
Sri Raghavendra Educational Institutions Society(R)
PROGRAM: 1
Implement and Demonstrate Depth First Search Algorithm on Water Jug Problem
import queue
import time
import random
dfsq = queue.Queue()
class node:
def __init__(self, data):
self.x = 0
self.y = 0
self.parent = data
def printnode(self):
print("(", self.x, ",", self.y, ")")
def generateAllSuccessors(self,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 = self.operation(cnode, rule_no)
if nextnode != None and not self.IsNodeInlist(nextnode, visitednodelist):
list1.append(nextnode)
return list1
def operation(self, cnode, rule):
x = cnode.x
Sri Raghavendra Educational Institutions Society(R)
y = cnode.y
if rule == 1:
if x < maxjug1:
x = maxjug1
else:
return None
elif rule == 2:
if y < maxjug2:
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
Sri Raghavendra Educational Institutions Society(R)
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
def pushlist(self, list1):
for m in list1:
Sri Raghavendra Educational Institutions Society(R)
dfsq.put(m)
def popnode(self):
if (dfsq.empty()):
return None
else:
return dfsq.get()
def isGoalNode(self, cnode, gnode):
if (cnode.x == gnode.x and cnode.y == gnode.y):
return True
return False
def dfsMain(self,initialNode, GoalNode):
dfsq.put(initialNode)
while not dfsq.empty():
visited_node = self.popnode()
print("Pop node:")
visited_node.printnode()
if self.isGoalNode(visited_node, GoalNode):
return visited_node
successor_nodes = self.generateAllSuccessors(visited_node)
self.pushlist(successor_nodes)
return None
def IsNodeInlist(self, cnode, list1):
for m in list1:
if (cnode.x == m.x and cnode.y == m.y):
return True
return False
def printpath(self, cnode):
Sri Raghavendra Educational Institutions Society(R)
temp = cnode
#list2 = []
while (temp != None):
list2.append(temp)
temp = temp.parent
list2.reverse()
for i in list2:
i.printnode()
print("Path Cost:", len(list2))
if __name__ == '__main__':
list2 = []
visitednodelist = []
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()
node1 = node(None)
solutionNode = node1.dfsMain(initialNode, GoalNode)
end_time = time.time()
if (solutionNode != None):
Sri Raghavendra Educational Institutions Society(R)
Output:
Enter the value of Maxjug1: 5
Enter the 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
Execution Time: 70518.57161521912 ms
Sri Raghavendra Educational Institutions Society(R)
PROGARM 2
Implement and Demonstrate Best First Search Algorithm on Missionaries-Cannibals
Problems using Python
import copy
class CoastState:
def __init__(self, c, m):
self.cannibals = c
self.missionaries = m
# 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
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 = ""
Sri Raghavendra Educational Institutions Society(R)
temp = copy.deepcopy(self.data)
if self.data["boat"] == "left":
coast = "left"
across_coast = "right"
elif self.data["boat"] == "right":
coast = "right"
across_coast = "left"
# 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)
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)
temp = copy.deepcopy(self.data)
# MOVING 1 CANNIBAL (C)
Sri Raghavendra Educational Institutions Society(R)
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():
child = GameState(temp)
child.parent = self
children.append(child)
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)
Sri Raghavendra Educational Institutions Society(R)
child.parent = self
children.append(child)
return children
def breadth_first_search(self):
left = CoastState(3, 3)
right = CoastState(0, 0)
root_data = {"left": left, "right": right, "boat": "left"}
explored = []
nodes = []
path = []
nodes.append(GameState(root_data))
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(self, g):
path = [g]
while g.parent:
g = g.parent
path.append(g)
Sri Raghavendra Educational Institutions Society(R)
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!")
def main(self):
solution = self.breadth_first_search()
print("Missionaries and Cannibals AI Problem Solution using Breath - First Search:")
self.print_path(solution)
if __name__ == "__main__":
mc = GameState(None)
mc.main()
Output:
Missionaries and Cannibals AI Problem Solution using Breath - First Search:
Left Side Right Side Boat
Cannibals Missionaries Cannibals MissionariesBoat Position
State 0 Left C: 3. Left M: 3. | Right C: 0. Right M: 0. | Boat: left
State 1 Left C: 1. Left M: 3. | Right C: 2. Right M: 0.
| Boat: right State 2 Left C: 2. Left M: 3. | Right C: 1.
Right M: 0. | Boat: left
State 3 Left C: 0. Left M: 3. | Right C: 3. Right M: 0.
| Boat: right State 4 Left C: 1. Left M: 3. | Right C: 2.
Right M: 0. | Boat: left
Sri Raghavendra Educational Institutions Society(R)
PROGRAM 3
def __init__(self,adjac_lis):
self.adjac_lis = adjac_lis
def get_neighbours(self,v):
return self.adjac_lis[v]
def h(self,n):
H = {'A':1,'B':1, 'C':1,'D':1}
return H[n]
def a_star_algorithm(self,start,stop):
open_lst = set([start])
closed_lst = set([])
dist = {}
dist[start] = 0
prenode = {}
prenode[start] = start
n = None
for v in open_lst:
Sri Raghavendra Educational Institutions Society(R)
n = v;
if n == None:
return None
if n == stop:
reconst_path = []
while prenode[n] != n:
reconst_path.append(n)
n = prenode[n]
reconst_path.append(start)
reconst_path.reverse()
return reconst_path
open_lst.add(m)
prenode[m] = n
else:
prenode[m] = n
if m in closed_lst:
closed_lst.remove(m)
open_lst.add(m)
open_lst.remove(n)
closed_lst.add(n)
return None
adjac_lis ={'A':[('B',1),('C',3),('D',7)],'B':[('D',5)],'C':[('D',12)]}
graph1=Graph(adjac_lis)
graph1.a_star_algorithm('A', 'D')
OUTPUT
Out[2]:
PROGRAM: 4
Implement AO* Search algorithm
def recAOStar(n):
global finalPath
print("Expanding Node:",n)
and_nodes = []
or_nodes =[]
if(n in allNodes):
if 'AND' in allNodes[n]:
and_nodes = allNodes[n]['AND']
if 'OR' in allNodes[n]:
or_nodes = allNodes[n]['OR']
if len(and_nodes)==0 and len(or_nodes)==0:
return
solvable = False
marked ={}
while not solvable:
if len(marked)==len(and_nodes)+len(or_nodes):
min_cost_least,min_cost_group_least = least_cost_group(and_nodes,or_nodes,{})
solvable = True
change_heuristic(n,min_cost_least)
optimal_child_group[n] = min_cost_group_least
continue
min_cost,min_cost_group = least_cost_group(and_nodes,or_nodes,marked)
is_expanded = False
if len(min_cost_group)>1:
Sri Raghavendra Educational Institutions Society(R)
if(min_cost_group[0] in allNodes):
is_expanded = True
recAOStar(min_cost_group[0])
if(min_cost_group[1] in allNodes):
is_expanded = True
recAOStar(min_cost_group[1])
else:
if(min_cost_group in allNodes):
is_expanded = True
recAOStar(min_cost_group)
if is_expanded:
min_cost_verify, min_cost_group_verify = least_cost_group(and_nodes, or_nodes, {})
if min_cost_group == min_cost_group_verify:
solvable = True
change_heuristic(n, min_cost_verify)
optimal_child_group[n] = min_cost_group
else:
solvable = True
change_heuristic(n, min_cost)
optimal_child_group[n] = min_cost_group
marked[min_cost_group]=1
return heuristic(n)
def least_cost_group(and_nodes, or_nodes, marked):
node_wise_cost = {}
for node_pair in and_nodes:
if not node_pair[0] + node_pair[1] in marked:
Sri Raghavendra Educational Institutions Society(R)
cost = 0
cost = cost + heuristic(node_pair[0]) + heuristic(node_pair[1]) + 2
node_wise_cost[node_pair[0] + node_pair[1]] = cost
for node in or_nodes:
if not node in marked:
cost = 0
cost = cost + heuristic(node) + 1
node_wise_cost[node] = cost
min_cost = 999999
min_cost_group = None
for costKey in node_wise_cost:
if node_wise_cost[costKey] < min_cost:
min_cost = node_wise_cost[costKey]
min_cost_group = costKey
return [min_cost, min_cost_group]
def heuristic(n):
return H_dist[n]
def change_heuristic(n, cost):
H_dist[n] = cost
return
def print_path(node):
print(optimal_child_group[node], end="")
node = optimal_child_group[node]
if len(node) > 1:
if node[0] in optimal_child_group:
print("->", end="")
Sri Raghavendra Educational Institutions Society(R)
print_path(node[0])
if node[1] in optimal_child_group:
print("->", end="")
print_path(node[1])
else:
if node in optimal_child_group:
print("->", end="")
print_path(node)
H_dist = {
'A': -1,
'B': 4,
'C': 2,
'D': 3,
'E': 6,
'F': 8,
'G': 2,
'H': 0,
'I': 0,
'J': 0
}
allNodes = {
'A': {'AND': [('C', 'D')], 'OR': ['B']},
'B': {'OR': ['E', 'F']},
'C': {'OR': ['G'], 'AND': [('H', 'I')]},
'D': {'OR': ['J']}
}
Sri Raghavendra Educational Institutions Society(R)
optimal_child_group = {}
optimal_cost = recAOStar('A')
print('Nodes which gives optimal cost are')
print_path('A')
print('\nOptimal Cost is :: ', optimal_cost)
OUTPUT
Expanding Node: A
Expanding Node: B
Expanding Node: C
Expanding Node: D
Nodes which gives optimal cost are
CD->HI->J
Optimal Cost is :: 5
Sri Raghavendra Educational Institutions Society(R)
PROGRAM 5
for i in board:
print (i)
Output:
Enter the number of queens
8
[1, 0, 0, 0, 0, 0, 0, 0]
[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]
Sri Raghavendra Educational Institutions Society(R)
PROGRAM 6
Implementation of TSP using heuristic approach
# Traveling Salesman Problem using
# Branch and Bound.
import math
maxsize = float('inf')
# 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]
# 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:
Sri Raghavendra Educational Institutions Society(R)
second = first
first = adj[i][j]
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
# 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_res has the total weight
# of the solution we got
curr_res = curr_weight + adj[curr_path[level - 1]][curr_path[0]]
if curr_res < final_res:
copyToFinal(curr_path)
final_res = curr_res
return
# for any other level iterate for all vertices
Sri Raghavendra Educational Institutions Society(R)
Output:
Minimum cost: 25
Path Taken: 0 2 3 1 0
Sri Raghavendra Educational Institutions Society(R)
PROGRAM 7
Implementation of the problem solving strategies: either using Forward Chaining or
Backward Chaining.
print()
print(' 2)Facts')
print(' ', end='')
for i in Fact:
print(i,' ',end='')
print();print()
print(' 3)Goal')
print(' ', Goal)
# -------------------------------------
Path=[]
Flag=[]
origin_fact = copy.deepcopy(Fact)
print('PART2. Trace')
# 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
itdoesn't work even after finishing it.
count += 1
print(' ', end='')
print('ITERATION',count)
Sri Raghavendra Educational Institutions Society(R)
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='')
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
Sri Raghavendra Educational Institutions Society(R)
break
else:
print(', not applied, because of lacking ', v)
break
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
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:
Sri Raghavendra Educational Institutions Society(R)
Output:
Enter the file name: test.txt
PART1. Data
1)Rules
R 1 : A -> L
R 2 : L -> K
R 3 : D -> A
R 4 : D -> M
R 5 : F B -> Z
R 6 : C D -> F
R 7 : A -> D
2)Facts
A B C
3)Goal
Z
PART2. Trace
ITERATION 1
R 1 : A -> L, apply, Raise flag1. Facts A B C L
PART3. Results
1) Goal Z not achieved
ITERATION 2
R 1 : A -> L, skip, because flag1 raised
Sri Raghavendra Educational Institutions Society(R)
PART3. Results
1) Goal Z not achieved
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 PART3. Results
1) Goal Z not achieved
ITERATION 4
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
PART3. Results
1) Goal Z not achieved
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
Sri Raghavendra Educational Institutions Society(R)
PART3. Results
1) Goal Z not achieved
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
PART3. Results
1) Goal Z achieved
2) Path: R 1 R 2 R 7 R 4 R 6 R 5
Sri Raghavendra Educational Institutions Society(R)
PROGRAM: 8
Implement resolution principle on FOPL related problems
import time
start_time = time.time()
import re
import itertools
import collections
import copy
import queue
p=open("input4.txt","r")
data=list()
data1= p.readlines()
count=0
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()
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]
Sri Raghavendra Educational Institutions Society(R)
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])
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 :
Sri Raghavendra Educational Institutions Society(R)
if(newsentence[i]==',' or newsentence[i]=='('):
if newsentence[i+1] not in capitalVariables:
j=i+1
while(newsentence[j]!=',' and newsentence[j]!=')' ):
j+=1
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
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
Sri Raghavendra Educational Institutions Society(R)
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
newsentence=newsentence[:i+1]+'x'+newsentence[j:]
i+=1
repeatflag=repeatedsentencecheck.get(newsentence)
if repeatflag :
return True
repeatedsentencecheck[newsentence]=1
Sri Raghavendra Educational Institutions Society(R)
return False
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(" ","")
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:
Sri Raghavendra Educational Institutions Society(R)
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 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]
Sri Raghavendra Educational Institutions Society(R)
def resolution():
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:
Sri Raghavendra Educational Institutions Society(R)
ans='~'+qr
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:
Sri Raghavendra Educational Institutions Society(R)
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]
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:
Sri Raghavendra Educational Institutions Society(R)
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]]:
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)
Sri Raghavendra Educational Institutions Society(R)
if(currentanswer=="TRUE"):
break
if(currentanswer=="TRUE"):
break
if(counter==2000 or (time.time()-query_start)>20):
break
answer.append(currentanswer)
return answer
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:
Input1.txt 1
Take(Alice,NSAIDs)
Take(Alice,Warfarin)
Input1.txt FALSE
Sri Raghavendra Educational Institutions Society(R)
Input2.txt
2
Alert(Bob,NSAIDs)
Alert(Bob,VitC)
5
Take(x,Warfarin) => ~Take(x,NSAIDs)
HighBP(x) => Alert(x,NSAIDs)
Take(Bob,Antacids)
Take(Bob,VitA)
HighBP(Bob)
Output2.txt
TRUE
FALSE
Input3.txt
3
Alert(Alice,VitE)
Alert(Bob,VitE)
Alert(John,VitE)
9
Migraine(x) & HighBP(x) => Take(x,Timolol)
Take(x,Warfarin) & Take(x,Timolol) => Alert(x,VitE)
Migraine(Alice)
Migraine(Bob)
HighBP(Bob)
OldAge(John)
HighBP(John)
Sri Raghavendra Educational Institutions Society(R)
Take(John,Timolol)
Take(Bob,Warfarin)
Output3.txt
FALSE
TRUE
FALSE
Input4.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)
Output4.txt
FLASE
Input5.txt
6
F(Bob)
H(John)
~H(Alice)
~H(John)
G(Bob)
Sri Raghavendra Educational Institutions Society(R)
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)
Output5.txt
FALSE
TRUE
TRUE
FALSE
FALSE
TRUE
Sri Raghavendra Educational Institutions Society(R)
PROGRAM 9
Implement Tic-Tac-Toe game using Python\
theBoard = {'7': ' ' , '8': ' ' , '9': ' ' ,
'4': ' ' , '5': ' ' , '6': ' ' ,
'1': ' ' , '2': ' ' , '3': ' ' }
board_keys = []
for key in theBoard:
board_keys.append(key)
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
Sri Raghavendra Educational Institutions Society(R)
else:
print("That place is already filled.\nMove to which place?")
continue
# 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)
Sri Raghavendra Educational Institutions Society(R)
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
# 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!!")
turn = 'X'
# 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] = " "
game()
if __name__ == "__main__":
game()
Output:
| |
-+-+-
| |
-+-+-
| |
It's your turn,X.Move to which place?
4
| |
-+-+-
X| |
-+-+-
| |
It's your turn,O.Move to which place?
3
| |
-+-+-
X| |
-+-+-
| |O
It's your turn,X.Move to which place?
5
| |
-+-+- X|X|
-+-+-
| |O
Sri Raghavendra Educational Institutions Society(R)
Game Over.
2
X| |
-+-+-
| |X
-+-+- |O|O
It's your turn,X.Move to which place?
8
X|X|
-+-+-
| |X
-+-+- |O|O
It's your turn,O.Move to which place?
1
X|X|
-+-+-
| |X
-+-+- O|O|O
Game Over.
STUDENT ASSESSMENT :
PROGRAM 10
Build a bot which provides all the information related to text in search box
PROGRAM 11
Implement any Game and demonstrate the Game playing strategies