Professional Documents
Culture Documents
ARTIFICIAL INTELLIGENCE
SEMESTER VI
NAME –
REG NO -
KANCHEEPURAM DISTRICT
BONAFIDE CERTIFICATE
Register No
Lab Incharge
1
Implementation of Tic-Tac-Toe problem
2 Implementation of 8 puzzle problem
Algorithm:
1. Start
2. Ask user to choose between ‘X’ or ‘O’
3. Display Empty board.
4. Ask the user to input a position and display the board with the sign in that position.
5. Continue the game with alternative turns between user and computer.
6. Check for win, draw or loose condition.
7. Display result.
8. Stop.
SOURCE CODE:
import random
#if computer cannot win or ruin a winning, then it will choose a random position starting
#with the corners, the center then the edges
if position == -1:
for i in range(len(board)):
#an empty index on the board
if board[i]==" ":
if i in [1,3,7,9]:
available_corners.append(i)
if i is 5:
available_center.append(i)
if i in [2,4,6,8]:
available_edges.append(i)
#check corners first
if len(available_corners)>0:
print("it comes here")
#select a random position in the corners
position=random.choice(available_corners)
#then check the availability of the center
elif len(available_center)>0:
#select the center as the position
position=available_center[0]
#lastly, check the availability of the edges
elif len(available_edges)>0:
#select a random position in the edges
position=random.choice(available_edges)
#fill the position with the letter
board[position]=computer_letter
except:
position=int(input("PLEASE enter position using only NUMBERS from 1-9: "))
#put the letter in the selected position & computer plays then draw the board
insert_letter(board,letter,position)
#computer move
computer_move(board,auto_letter)
#draw the board
board=draw_board(board)
if is_winner(board,letter):
print("Congratulations! You Won.")
return repeat_game()
elif is_winner(board,auto_letter):
print("Hard Luck! Computer won")
return repeat_game()
OUTPUT:
RESULT:Tic-Tac-Toe for single player using python has been successfully implemented.
Date:- 8-Puzzle Problem
Expt.No:- 02
SOURCE CODE:
pip install colorama
#direction matrix
DIRECTIONS = {"U": [-1, 0], "D": [1, 0], "L": [0, -1], "R": [0, 1]}
#target matrix
#bar color
first_line = Style.BRIGHT + Fore.CYAN + left_up_angle + dash + dash + dash + top_junction + dash + dash + dash +
top_junction + dash + dash + dash + right_up_angle + Fore.RESET + Style.RESET_ALL middle_line = Style.BRIGHT +
Fore.CYAN + left_junction + dash + dash + dash + middle_junction + dash + dash + dash + middle_junction + dash + dash
+ dash + right_junction + Fore.RESET +
Style.RESET_ALL
last_line = Style.BRIGHT + Fore.CYAN + left_down_angle + dash + dash + dash + bottom_junction + dash + dash + dash
+ bottom_junction + dash + dash + dash + right_down_angle + Fore.RESET +
Style.RESET_ALL
print(first_line)
for a in range(len(array)):
for i in array[a]:
if i == 0:
print(bar) if a == 2:
print(last_line) else:
print(middle_line)
#it is the node which store each state of puzzle class Node:
def f(self):
if element in current_state[row]:
cost = 0
emptyPos = get_pos(node.current_node, 0)
dir))
return listNode
return bestNode
'dir': node.dir,
'node': node.current_node
})
'node': node.current_node
})
while True:
if test_node.current_node == END:
return buildPath(closed_set)
open_set[str(test_node.current_node)]
br = main([[1, 2, 4],
[3, 5, 7],
[6, 8, 0]])
print()
ALGORITHM:
1. Start the program.
2. Ask user to input entries where 1-Dirty and 0 - clean.
3. Clean the room using vacuum operation.
4. Display Cost.
5. Stop.
SOURCE CODE:
import random
def display(room):
print(room)
room = []
print("enter entries")
x =0
y= 0
ALGORITHM
1. Put any of the graph vertices at end of queue.
2. Take front item of queue and add to visited set.
3. Create an adjacencylist for that vertex adjacent nodes. Add those which are not in the visited
set to the rear of the queue.
4. Repeat step 2 and 3 till queue is empty.
SOURCE CODE:
result = []
while queue:
v = queue[0]
result.append(v)
queue = queue[1:]
for neighbor in adjacencyList[v]:
if neighbor not in visitedSet:
visitedSet.add(neighbor)
queue.append(neighbor)
return result
print(bfs(adjacencyList, 'A'))
OUTPUT:
ALGORITHM:
1. Declare graph.
2. Put source node on top of stack.
3. Take top item of stack and append to path and mark as visited.
4. Add all neighbors to stack.
5. Pop element from stack and check if it is visited.
6. If not visited add to path and all neighbors to stack.
7. Display Path.
SOURCE CODE:
graph = {"A":["D","C","B"],
"B":["E"],
"C":["G","F"],
"D":["H"],
"E":["I"],
"F":["J"]}
def dfs_non_recursive(graph, source):
if source is None or source not in graph:
return "Invalid input"
path = []
stack = [source]
while(len(stack) != 0):
s = stack.pop()
if s not in path:
path.append(s)
if s not in graph:
#leaf node
continue
for neighbor in graph[s]:
stack.append(neighbor)
return " ".join(path)
DFS_path = dfs_non_recursive(graph, "A")
print(DFS_path)
OUTPUT
AIM: Implementation of A* algorithm to find out the path for the maze.
ALGORITHM:
1. Define method to take actions.
2. Calculate state based on actions.
3. Check if we reached the goal.
4. Use heuristic function to calculate cost.
5. Display Result.
SOURCE CODE:
import math
from simpleai.search import SearchProblem, astar
for y in range(len(self.board)):
for x in range(len(self.board[y])):
if self.board[y][x].lower() == "o":
self.initial = (x, y)
elif self.board[y][x].lower() == "x":
self.goal = (x, y)
super(MazeSolver, self).__init__(initial_state=self.initial)
return actions
if action.count("up"):
y -= 1
if action.count("down"):
y += 1
if action.count("left"):
x -= 1
if action.count("right"):
x += 1
new_state = (x, y)
return new_state
if __name__ == "__main__":
# Define the map
MAP = """
##############################
# # # #
# #### ######## # #
# o # # # #
# ### ##### ###### #
# # ### # #
# # # # # # ###
# ##### # # # x #
# # # #
##############################
"""
print()
Output:
RESULT: A* algorithm to find out the path for the maze has been successfully implemented.
DATE: Constraints Satisfaction Problem
EXPT.NO: 07
ALGORITHM:
1. Identify variables.
2. Identify Constraints.
3. If all characters are assigned, return true if puzzle is solved, false otherwise
4. Otherwise, consider the first unassigned character
5. for (every possible choice among the digits not in use)
make that choice and then recursively try to assign the rest of the characters
if recursion successful, return true
if !successful, unmake assignment and try another digit
6. If all digits have been tried and nothing worked, return false to trigger backtracking.
SOURCE CODE:
def factorial(n):
if(n==1):
return 1
else:
return (n * factorial(n-1))
class CSP_crypt:
def __init__(self,str):
p = str.split();
self.p1=p[0]
self.p2=p[2]
self.p3=p[4]
self.opr = p[1]
self.state = []
self.solved = False
for q in self.p1:
if(not(q in self.state)):
self.state.append(q)
for q in self.p2:
if(not(q in self.state)):
self.state.append(q)
for q in self.p3:
if(not(q in self.state)):
self.state.append(q)
for i in range(10-len(self.state)):
self.state.append('x')
def display(self):
print("Line 1 : ", self.p1)
print("Line 2 : ", self.p2)
print("Line 3 : ", self.p3)
print("Operation : ", self.opr)
print("State : ", self.state)
print("Solved : ", self.solved)
def display_ans(self):
for i in self.state:
if(not(i == 'x')):
print(i," - ",self.state.index(i))
def apply_constraints(self,depth):
if((len(self.p3) > len(self.p1)) and (len(self.p3) > len(self.p2))):
if(self.state[0] == self.p3[0]):
return True
if(self.state[1] == self.p3[0]):
return True
elif(depth < 2):
return True
else:
return True
return False
def get_number(self,p):
num = 0
for q in p:
num = num*10
num = num + self.state.index(q)
return num
def solve(self):
num1 = self.get_number(self.p1)
num2 = self.get_number(self.p2)
num3 = self.get_number(self.p3)
if(self.opr == '+'):
ans = num1 + num2
elif(self.opr == '-'):
ans = num1 - num2
elif(self.opr == '*'):
ans = num1 * num2
elif(self.opr == '/'):
ans = num1 / num2
#print("ans = ",ans)
if(ans == num3):
print("ans = ",ans)
print("num1 = ",num1)
print("num2 = ",num2)
print("num3 = ",num3)
self.solved = True
def expand(self,l,r,depth):
self.solve()
if(self.solved == True):
return
elif(l == r):
return
else:
for i in range(l,r+1):
self.state[l],self.state[i] = self.state[i],self.state[l]
if(self.apply_constraints(depth)):
depth = depth + 1
self.expand(l+1,r,depth)
depth = depth - 1
if(self.solved == True):
return
self.state[i],self.state[l] = self.state[l],self.state[i]
if(__name__=="__main__"):
c_csp.display()
c_csp.expand(0,9,0)
c_csp.display()
if(c_csp.solved == True):
c_csp.display_ans()
OUTPUT:
ALGORITHM:
1. If the game is over, return the score from X's perspective.
2. Otherwise get a list of new game states for every possible move
3. Create a scores list
4. For each of these states add the minimax result of that state to the scores list
5. If it's X's turn, return the maximum score from the scores list
6. If it's O's turn, return the minimum score from the scores list
SOURCE CODE:
#!/usr/bin/env python3
from math import inf as infinity
from random import choice
import platform
import time
from os import system
HUMAN = -1
COMP = +1
board = [
[0, 0, 0],
[0, 0, 0],
[0, 0, 0],
]
def evaluate(state):
if wins(state, COMP):
score = +1
elif wins(state, HUMAN):
score = -1
else:
score = 0
return score
def game_over(state):
def empty_cells(state):
cells = []
return cells
if [x, y] in empty_cells(board):
return True
else:
return False
if valid_move(x, y):
board[x][y] = player
return True
else:
return False
if depth == 0 or game_over(state):
score = evaluate(state)
return [-1, -1, score]
if player == COMP:
if score[2] > best[2]:
best = score # max value
else:
if score[2] < best[2]:
best = score # min value
return best
def clean():
"""
Clears the console
"""
os_name = platform.system().lower()
if 'windows' in os_name:
system('cls')
else:
system('clear')
chars = {
-1: h_choice,
+1: c_choice,
0: ' '
}
str_line = '---------------'
print('\n' + str_line)
for row in state:
for cell in row:
symbol = chars[cell]
print(f'| {symbol} |', end='')
print('\n' + str_line)
clean()
print(f'Computer turn [{c_choice}]')
render(board, c_choice, h_choice)
if depth == 9:
x = choice([0, 1, 2])
y = choice([0, 1, 2])
else:
move = minimax(board, depth, COMP)
x, y = move[0], move[1]
set_move(x, y, COMP)
time.sleep(1)
clean()
print(f'Human turn [{h_choice}]')
render(board, c_choice, h_choice)
if not can_move:
print('Bad move')
move = -1
except (EOFError, KeyboardInterrupt):
print('Bye')
exit()
except (KeyError, ValueError):
print('Bad choice')
def main():
"""
Main function that calls all functions
"""
clean()
h_choice = '' # X or O
c_choice = '' # X or O
first = '' # if human is the first
human_turn(c_choice, h_choice)
ai_turn(c_choice, h_choice)
# Game over message
if wins(board, HUMAN):
clean()
print(f'Human turn [{h_choice}]')
render(board, c_choice, h_choice)
print('YOU WIN!')
elif wins(board, COMP):
clean()
print(f'Computer turn [{c_choice}]')
render(board, c_choice, h_choice)
print('YOU LOSE!')
else:
clean()
render(board, c_choice, h_choice)
print('DRAW!')
exit()
if __name__ == '__main__':
main()
OUTPUT:
RESULT: Min max algorithm for an application (Tic-Tac-Toe) has been successfully
implemented.
Date Unification & Resolution
Expt.No:- 09
Algorithm:
Unification:
Step. 1: If Ψ1 or Ψ2 is a variable or constant, then:
a) If Ψ1 or Ψ2 are identical, then return NIL.
b) Else if Ψ1is a variable,
a. then if Ψ1 occurs in Ψ2, then return FAILURE
b. Else return { (Ψ2/ Ψ1)}.
c) Else if Ψ2 is a variable,
a. If Ψ2 occurs in Ψ1 then return FAILURE,
b. Else return {( Ψ1/ Ψ2)}.
d) Else return FAILURE.
Step.2: If the initial Predicate symbol in Ψ1 and Ψ2 are not same, then return FAILURE.
Step. 3: IF Ψ1 and Ψ2 have a different number of arguments, then return FAILURE.
Step. 4: Set Substitution set(SUBST) to NIL.
Step. 5: For i=1 to the number of elements in Ψ1.
a) Call Unify function with the ith element of Ψ1 and ith element of Ψ2, and put the result into S.
b) If S = failure then returns Failure
c) If S ≠ NIL then do,
a. Apply S to the remainder of both L1 and L2.
b. SUBST= APPEND(S, SUBST).
Step.6: Return SUBST.
Resolution
1. Conversion of facts into first-order logic.
2. Convert FOL statements into CNF
3. Negate the statement which needs to prove (proof by contradiction)
4. Draw resolution graph (unification).
SOURCE CODE:
input.txt:
1
Criminal(West)
7
~American(x) | ~Weapon(y) | ~Sells(x,y,z) | ~Enemy(z,America) | Criminal(x)
Owns(Nono,M1)
Missile(M1)
~Missile(x) | ~Owns(Nono,x) | Sells(West,x,Nono)
~Missile(x) | Weapon(x)
Enemy(Nono,America)
American(West)
Unification:
import copy
import time
class Parameter:
variable_count = 1
def __init__(self, name=None):
if name:
self.type = "Constant"
self.name = name
else:
self.type = "Variable"
self.name = "v" + str(Parameter.variable_count)
Parameter.variable_count += 1
def isConstant(self):
return self.type == "Constant"
def __str__(self):
return self.name
class Predicate:
def __init__(self, name, params):
self.name = name
self.params = params
def __str__(self):
return self.name + "(" + ",".join(str(x) for x in self.params) + ")"
def getNegatedPredicate(self):
return Predicate(negatePredicate(self.name), self.params)
class Sentence:
sentence_count = 0
params.append(new_param)
self.predicates.append(Predicate(name, params))
def getPredicates(self):
return [predicate.name for predicate in self.predicates]
def containsVariable(self):
return any(not param.isConstant() for param in self.variable_map.values())
def __str__(self):
return "".join([str(predicate) for predicate in self.predicates])
class KB:
def __init__(self, inputSentences):
self.inputSentences = [x.replace(" ", "") for x in inputSentences]
self.sentences = []
self.sentence_map = {}
def prepareKB(self):
self.convertSentencesToCNF()
for sentence_string in self.inputSentences:
sentence = Sentence(sentence_string)
for predicate in sentence.getPredicates():
self.sentence_map[predicate] = self.sentence_map.get(predicate, []) +
[sentence]
def convertSentencesToCNF(self):
for sentenceIdx in range(len(self.inputSentences)):
if "=>" in self.inputSentences[sentenceIdx]: # Do negation of the Premise
and add them as literal
self.inputSentences[sentenceIdx] =
negateAntecedent(self.inputSentences[sentenceIdx])
try:
result = self.resolve([negatedPredicate],
[False]*(len(self.inputSentences) + 1))
except:
result = False
self.sentence_map = prev_sentence_map
if result:
results.append("TRUE")
else:
results.append("FALSE")
return results
canUnify, substitution =
performUnification(copy.deepcopy(queryPredicate), copy.deepcopy(kbPredicate))
if canUnify:
newSentence = copy.deepcopy(kb_sentence)
newSentence.removePredicate(kbPredicate)
newQueryStack = copy.deepcopy(queryStack)
if substitution:
for old, new in substitution.items():
if old in newSentence.variable_map:
parameter = newSentence.variable_map[old]
newSentence.variable_map.pop(old)
parameter.unify("Variable" if
new[0].islower() else "Constant", new)
newSentence.variable_map[new] = parameter
new_visited = copy.deepcopy(visited)
if kb_sentence.containsVariable() and
len(kb_sentence.predicates) > 1:
new_visited[kb_sentence.sentence_index] = True
def negatePredicate(predicate):
return predicate[1:] if predicate[0] == "~" else "~" + predicate
def negateAntecedent(sentence):
antecedent = sentence[:sentence.find("=>")]
premise = []
premise.append(sentence[sentence.find("=>") + 2:])
return "|".join(premise)
def getInput(filename):
with open(filename, "r") as file:
noOfQueries = int(file.readline().strip())
inputQueries = [file.readline().strip() for _ in range(noOfQueries)]
noOfSentences = int(file.readline().strip())
inputSentences = [file.readline().strip() for _ in range(noOfSentences)]
return inputQueries, inputSentences
if __name__ == '__main__':
inputQueries_, inputSentences_ = getInput("input.txt")
knowledgeBase = KB(inputSentences_)
knowledgeBase.prepareKB()
results_ = knowledgeBase.askQueries(inputQueries_)
printOutput("output.txt", results_)
Resolution:
import time
start_time = time.time()
import re
import itertools
import collections
import copy
import queue
p=open("input.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])
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
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:
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("\||&|=>")
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 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(ansclausespredica
te[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
if __name__ == '__main__':
finalanswer=resolution()
o=open("output2.txt","w+")
wc=0
while(wc < n-1):
o.write(finalanswer[wc]+"\n")
wc+=1
o.write(finalanswer[wc])
o.close()
OUTPUT:
RESULT: Unification and Resolution have been successfully implemented for the real world
problem.
Date Blocks-World Problem
Expt.No:-10
ALGORITHM:
1. Select a move.
2. Move the top block to a stack, if the diff is not reduced, then move it to the
temp_table.
3. Move the top block to the temp_table, skip if it is already on the table .
4. Check current state with goal state.
5. If goal reached stop, else continue step 2 and 3.
SOURCE CODE:
BlockWorldAgent.py:
import copy
import time
class BlockWorldAgent:
def __init__(self):
pass
start = time.time()
class State:
def __init__(self, first_stack, second_stack, total_num, moves=None):
if moves is None:
moves = []
self.first_stack = first_stack
self.second_stack = second_stack
self.total_num = total_num
self.moves = moves
def goal_state_move(self):
while self.difference() != 0:
self = self.select_move()
return self.moves
# move the top block to the temp_table, skip if it is already on the table (itself alone on a table)
for index, stack in enumerate(self.first_stack):
if len(stack) > 1: # not it self alone
curr_table, move = self.valid_state_move(self.first_stack, index, -1) # -1 means table
new_state = State(curr_table, self.second_stack, self.total_num, copy.copy(self.moves))
new_state.moves.append(move)
if new_state.difference() <= self.difference():
return new_state
if len(left) == 0:
temp_table.remove(left)
return temp_table, move
def difference(self):
same_num = 0
# compare each stack on two stacks
for left in self.first_stack:
for right in self.second_stack:
index = 0
while index < len(left) and index < len(right):
if left[index] == right[index]:
same_num += 1
index += 1
else:
break
diff = self.total_num - same_num
return diff
total_num = 0
for ls in initial_arrangement:
for e in ls:
total_num += 1
state = State(initial_arrangement, goal_arrangement, total_num)
solution = state.goal_state_move()
end = time.time()
run_time = str((end - start) * 1000)
print("Running time:" + run_time + "ms")
return solution
Main.py:
from BlockWorldAgent import BlockWorldAgent
def test():
test_agent = BlockWorldAgent()
print(test_agent.solve(initial_arrangement_1, goal_arrangement_1))
if __name__ == "__main__":
test()
OUTPUT: