AI Lab MAnual Final
AI Lab MAnual Final
MANAGEMENT
Udayapura, Kanakapura Road, Bengaluru - 560082, Karnataka.
Lab Manual
Artificial Intelligence Laboratory
18AIL57
Prepared By:
Mrs. Sowbhagya M P
Asst. Prof. Dept. of AI&ML
Content
******************************************************************************
Course Learning Objectives: This course will enable students to:
Implement and evaluate AI algorithms in Python programming language.
*****************************************************************************
****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
Backward Chaining.
7.Implement resolution principle on FOPL related problems.
8.Implement any Game and demonstrate the Game playing strategies.
i) For laboratories having only one part – Procedure + Execution + Viva-Voce: 15+70+15 = 100
Marks
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(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
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
def pushlist(list1):
for m in list1:
dfsq.put(m)
def popnode():
if (dfsq.empty()):
return None
else:
return dfsq.get()
visitednodelist = []
def printpath(cnode):
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))
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")
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
# 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
class CoastState:
# 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:
if self.data["boat"] == "left":
coast = "left"
across_coast = "right"
elif self.data["boat"] == "right":
coast = "right"
across_coast = "left"
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)
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)
child.parent = self
children.append(child)
return children
def breadth_first_search():
left = CoastState(3, 3)
right = CoastState(0, 0)
root_data = {"left": left, "right": right, "boat": "left"}
explored = []
nodes = []
path = []
nodes.append(GameState(root_data))
def print_path(g):
path = [g]
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!")
def main():
solution = breadth_first_search()
print("Missionaries and Cannibals AI Problem Solution using Breath - First Search:")
print_path(solution)
Output:
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']
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}
{'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': []}
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
def printSolution(self):
print("FOR GRAPH SOLUTION, TRAVERSE THE GRAPH FROM THE START
NODE:",self.start)
print(" ")
print(self.solutionGraph)
print(" ")
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
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)
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
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
#chessboard
#NxN matrix with all elements 0
board = [[0]*N for _ in range(N)]
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
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
return False
N_queen(N)
for i in board:
print (i)
Output:
Output:
[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]
visited[i] = True
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 = ' ')
Output:
Minimum cost : 25
Path Taken : 0 2 3 1 0
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]
#
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])
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')
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
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:
print('1) Goal',Goal,' not achieved')
- Input: A text file that contains rules, fact and goal to deal with.
```
Test 1. Initial fact in right hand side
1) Rules
LA
K L
AD
MD
ZFB
FCD
DA
2) Facts
ABC
3) Goal
Z
```
forwardChaining.py
file: test1.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
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
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
```
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]
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 :
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
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
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:
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])
paramArray[index] = y
return paramArray
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
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]
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]]:
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
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)
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)
Output.txt TRUE
theBoard = {'7': ' ' , '8': ' ' , '9': ' ' ,
'4': ' ' , '5': ' ' , '6': ' ' ,
'1': ' ' , '2': ' ' , '3': ' ' }
board_keys = []
''' 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. '''
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()
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)
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!!")
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?
2
||
-+-+-
X| |
-+-+-
|X|O
It's your turn,O.Move to which place?
5
||
-+-+-
X|O|
-+-+-
|X|O
It's your turn,X.Move to which place?
6
||
-+-+-
X|O|X
-+-+-
|X|O
It's your turn,O.Move to which place?
7
O| |
-+-+-
X|O|X
-+-+-
|X|O
Game Over.
Viva Questions
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?
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.