You are on page 1of 59

18CSC365J

ARTIFICIAL INTELLIGENCE

SEMESTER VI

DEPARTMENT OF DATA SCIENCE AND BUSINESS SYSTEMS

NAME –
REG NO -

SRM INSTITUTE OF SCIENCE AND


TECHNOLOGY (Under SECTION 3 of the UGC
Act, 1956) S.R.M NAGAR, KATTANKULATHUR –
603203 KANCHEEPURAM DISTRICT
FACULTY OF ENGINEERING AND TECHNOLOGY

SRM INSTITUTE OF SCIENCE AND TECHNOLOGY

(Under SECTION 3 of the UGC Act, 1956)

S.R.M NAGAR, KATTANKULATHUR – 603203

KANCHEEPURAM DISTRICT

BONAFIDE CERTIFICATE
Register No

Certified to be the bonafide record of work done by of

B. Tech Degree course in the practical of

in SRM INSTITUTE OF SCIENCE AND TECHNOLOGY,

KATTANKULATHUR during the academic year

Lab Incharge

Date: Year Coordinator

Submitted for the University examination held on at SRM Institute of


Science and Technology, Kattankulathur, Chennai - 603203.

Date: ---------------- ------------------


Examiner - 1 Examiner - 2
INDEX

EXP NO TITLE DATE SIGN

1
Implementation of Tic-Tac-Toe problem
2 Implementation of 8 puzzle problem

3 Developing agent problems for real world


problems
4 Developing Best First Search in real world
problems
5 Developing Depth First Search in real world problems

6 Developing A* Algorithm in real world problems

7 Implementation of constraint satisfaction


problem
8 Implementation of Min-Max algorithm for an
application
9 Implementation of Unification and Resolution
for real world
10 Implementation of block world problem
Date: Tic-Tac-Toe
Expt.No: 01

AIM: To create Tic-Tac-Toe for single player using python.

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

#to ask user to choose a letter


def select_letter():
let=""
auto_let=""
#ask user to select a letter (X or O)
while(let != "x" and let != "o"):
let=input("Select X or O: ").replace(" ","").strip().lower()
if let == "x":
auto_let="o"
else:
auto_let="x"
return let, auto_let

#to prepare a clean board for the game


def clean_board():
#an empty board for X and O values
brd=[" " for x in range(10)]
return brd

#to check if board is full


def is_board_full(board):
return board.count(" ")==0

#to insert a letter (X or O) in a specific position


def insert_letter(board,letter,pos):
board[pos]=letter

#to take computer moves


def computer_move(board,letter):
computer_letter=letter
possible_moves=[]
available_corners=[]
available_edges=[]
available_center=[]
position=-1

#all possible moves


for i in range(1,len(board)):
if board[i] ==" ":
possible_moves.append(i)

#if the position can make X or O wins!


#the computer will choose it to win or ruin a winning of the user
for let in ["x","o"]:
for i in possible_moves:
board_copy=board[:]
board_copy[i] = let
if is_winner(board_copy,let):
position=i

#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

#to draw the board


def draw_board(board):
board[0]=-1
#draw first row
print(" | | ")
print(" "+board[1]+" | "+board[2]+" | "+board[3]+" ")
print(" | | ")
print("-"*11)
#draw second row
print(" | | ")
print(" "+board[4]+" | "+board[5]+" | "+board[6]+" ")
print(" | | ")
print("-"*11)
#draw third row
print(" | | ")
print(" "+board[7]+" | "+board[8]+" | "+board[9]+" ")
print(" | | ")
print("-"*11)
return board

#to check if a specific player is the winner


def is_winner(board,letter):
return (board[1] == letter and board[2] == letter and board[3] == letter) or \
(board[4] == letter and board[5] == letter and board[6] == letter) or \
(board[7] == letter and board[8] == letter and board[9] == letter) or \
(board[1] == letter and board[4] == letter and board[7] == letter) or \
(board[2] == letter and board[5] == letter and board[8] == letter) or \
(board[3] == letter and board[6] == letter and board[9] == letter) or \
(board[1] == letter and board[5] == letter and board[9] == letter) or \
(board[3] == letter and board[5] == letter and board[7] == letter)

#to repeat the game


def repeat_game():

repeat=input("Play again? Press y for yes and n for no: ")


while repeat != "n" and repeat != "y":
repeat=input("PLEASE, press y for yes and n for no: ")
return repeat

#to play the game


def play_game():

letter, auto_letter= select_letter()


#clean the board
board=clean_board()
board=draw_board(board)
#check if there are empty positions on the board
while is_board_full(board) == False:
try:
position=int(input("Select a position (1-9) to place an "+letter+" : " ))

except:
position=int(input("PLEASE enter position using only NUMBERS from 1-9: "))

#check if user selects out of range position


if position not in range(1,10):
position=int(input("Please, choose another position to place an "+letter+" from 1 to 9 :"))

#check if user selects an occupied position by X or O


if board[position] != " ":
position=int(input("Please, choose an empty position to place an "+letter+" from 1 to 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()

#if " " not in board:


if is_board_full(board):
print("Tie Game :)")
return repeat_game()
#Start the game
print("Welcome to Tic Tac Toe.")
repeat="y"
while(repeat=="y"):
repeat=play_game()

OUTPUT:
RESULT:Tic-Tac-Toe for single player using python has been successfully implemented.
Date:- 8-Puzzle Problem
Expt.No:- 02

AIM: Implementation of 8 puzzle problem.


Algorithm:
1. Create Direction matrix.
2. Draw puzzle.
3. Use cost function to check the difference between current and goal state.
4. Get the best node among all nodes present.
5. Print result.

SOURCE CODE:
pip install colorama

from copy import deepcopy

from colorama import Fore, Back, Style

#direction matrix

DIRECTIONS = {"U": [-1, 0], "D": [1, 0], "L": [0, -1], "R": [0, 1]}

#target matrix

END = [[1, 2, 3], [4, 5, 6], [7, 8, 0]]

# unicode for draw puzzle in command promt or terminal left_down_angle =


'\u2514'
right_down_angle = '\u2518' right_up_angle =
'\u2510' left_up_angle = '\u250C'

middle_junction = '\u253C' top_junction = '\u252C'


bottom_junction = '\u2534' right_junction =
'\u2524' left_junction = '\u251C'

#bar color

bar = Style.BRIGHT + Fore.CYAN + '\u2502' + Fore.RESET + Style.RESET_ALL dash = '\u2500'

#Line draw code

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

#puzzle print function def print_puzzle(array):

print(first_line)

for a in range(len(array)):

for i in array[a]:

if i == 0:

print(bar, Back.RED + ' ' + Back.RESET, end=' ') else:


print(bar, i, end=' ')

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 init (self, current_node, previous_node, g, h, dir):

self.current_node = current_node self.previous_node =


previous_node self.g = g
self.h = h self.dir = dir

def f(self):

return self.g + self.h

def get_pos(current_state, element): for row in


range(len(current_state)):

if element in current_state[row]:

return (row, current_state[row].index(element))

#it is a distance calculation algo def


euclidianCost(current_state):

cost = 0

for row in range(len(current_state)):

for col in range(len(current_state[0])):


pos = get_pos(END, current_state[row][col]) cost += abs(row -
pos[0]) + abs(col - pos[1])
return cost

#get adjucent Nodes def getAdjNode(node):


listNode = []

emptyPos = get_pos(node.current_node, 0)

for dir in DIRECTIONS.keys():

newPos = (emptyPos[0] + DIRECTIONS[dir][0], emptyPos[1] + DIRECTIONS[dir][1])


if 0 <= newPos[0] < len(node.current_node) and 0 <= newPos[1] < len(node.current_node[0]): newState =
deepcopy(node.current_node)
newState[emptyPos[0]][emptyPos[1]] = node.current_node[newPos[0]][newPos[1]]
newState[newPos[0]][newPos[1]] = 0
# listNode += [Node(newState, node.current_node, node.g + 1, euclidianCost(newState), dir)]
listNode.append(Node(newState, node.current_node, node.g + 1, euclidianCost(newState),

dir))

return listNode

#get the best node available among nodes

def getBestNode(openSet): firstIter = True

for node in openSet.values():

if firstIter or node.f() < bestF: firstIter = False


bestNode = node bestF = bestNode.f()

return bestNode

#this functionn create the smallest path def


buildPath(closedSet):
node = closedSet[str(END)] branch = list()

while node.dir: branch.append({

'dir': node.dir,

'node': node.current_node

})

node = closedSet[str(node.previous_node)] branch.append({


'dir': '',

'node': node.current_node
})

branch.reverse() return branch

#main function of node def main(puzzle):


open_set = {str(puzzle): Node(puzzle, puzzle, 0, euclidianCost(puzzle), "")} closed_set = {}

while True:

test_node = getBestNode(open_set) closed_set[str(test_node.current_node)] =


test_node

if test_node.current_node == END:

return buildPath(closed_set)

adj_node = getAdjNode(test_node) for node in adj_node:


if str(node.current_node) in closed_set.keys() or str(node.current_node) in open_set.keys() and open_set[
str(node.current_node)].f() < node.f(): continue
open_set[str(node.current_node)] = node del

open_set[str(test_node.current_node)]

if name == ' main ': #it is start matrix

br = main([[1, 2, 4],

[3, 5, 7],

[6, 8, 0]])

print('total steps : ', len(br) - 1) print()


print(dash + dash + right_junction, "INPUT", left_junction + dash + dash) for b in br:
if b['dir'] != '':
letter = ''
if b['dir'] == 'U':
letter = 'UP' elif b['dir'] == 'R':
letter = "RIGHT" elif b['dir'] == 'L':
letter = 'LEFT' elif b['dir'] == 'D':
letter = 'DOWN'
print(dash + dash + right_junction, letter, left_junction + dash + dash) print_puzzle(b['node'])

print()

print(dash + dash + right_junction, 'ABOVE IS THE OUTPUT', left_junction + dash + dash)


OUTPUT:
RESULT: 8-puzzle problem has been successfully implemented.
Date Toy Problem
Expt.No:- 03

AIM: Implementation of toy problems (examples: Vacuum world ).

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")

#print("All the rooom are dirty")


R=3
C=3
for i in range(R): # A for loop for row entries
a =[]
for j in range(C): # A for loop for column entries
a.append(int(input()))
room.append(a)
display(room)

x =0
y= 0

print("Before cleaning the room I detect all of these random dirts")


display(room)
x =0
y= 0
z=0
while x < 3:
while y < 3:
if room[x][y] == 1:
print("Vaccum in this location now,",x, y)
room[x][y] = 0
print("cleaned", x, y)
z+=1
y+=1
x+=1
y=0
print("cost = ",z)
display(room)
OUTPUT

RESULT: The vacuum world problem has been successfully solved .


Date BFS
Expt.No:- 04

AIM: Implementation of BFS for an application.

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:

from collections import defaultdict


def generateAdjacencyLst(edges):
adjacencyList = defaultdict(list)
for u, v in edges:
adjacencyList[u].append(v)
adjacencyList[v].append(u)
return adjacencyList
edges = [['A', 'B'], ['A', 'C'], ['B', 'D'], ['B', 'E'], ['C', 'F'], ['C', 'G'], ['D',
'H'], ['D', 'I'], ['E', 'J'], ['E', 'K'], ['F', 'L'], ['F', 'M']]
adjacencyList = generateAdjacencyLst(edges)
def bfs(adjacencyList, vertex):
visitedSet = set()
queue = []
visitedSet.add(vertex)
queue.append(vertex)

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:

RESULT: BFS for an application has been successfully implemented.


Date DFS
Expt.No:-05

AIM: Implementation of DFS for an application.

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

RESULT:DFS for an application was successfully implemented.


DATE:
EXPT.NO: 06 A* Algorithm

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

# Class containing the methods to solve the maze


class MazeSolver(SearchProblem):
# Initialize the class
def __init__(self, board):
self.board = board
self.goal = (0, 0)

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)

# Define the method that takes actions


# to arrive at the solution
def actions(self, state):
actions = []
for action in COSTS.keys():
newx, newy = self.result(state, action)
if self.board[newy][newx] != "#":
actions.append(action)

return actions

# Update the state based on the action


def result(self, state, action):
x, y = state

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

# Check if we have reached the goal


def is_goal(self, state):
return state == self.goal

# Compute the cost of taking an action


def cost(self, state, action, state2):
return COSTS[action]

# Heuristic that we use to arrive at the solution


def heuristic(self, state):
x, y = state
gx, gy = self.goal

return math.sqrt((x - gx) ** 2 + (y - gy) ** 2)

if __name__ == "__main__":
# Define the map
MAP = """
##############################
# # # #
# #### ######## # #
# o # # # #
# ### ##### ###### #
# # ### # #
# # # # # # ###
# ##### # # # x #
# # # #
##############################
"""

# Convert map to a list


print(MAP)
MAP = [list(x) for x in MAP.split("\n") if x]

# Define cost of moving around the map


cost_regular = 1.0
cost_diagonal = 1.7

# Create the cost dictionary


COSTS = {
"up": cost_regular,
"down": cost_regular,
"left": cost_regular,
"right": cost_regular,
"up left": cost_diagonal,
"up right": cost_diagonal,
"down left": cost_diagonal,
"down right": cost_diagonal,
}

# Create maze solver object


problem = MazeSolver(MAP)

# Run the solver


result = astar(problem, graph_search=True)

# Extract the path


path = [x[1] for x in result.path()]

# Print the result


print()
for y in range(len(MAP)):
for x in range(len(MAP[y])):
if (x, y) == problem.initial:
print('o', end='')
elif (x, y) == problem.goal:
print('x', end='')
elif (x, y) in path:
print('·', end='')
else:
print(MAP[y][x], end='')

print()
Output:

RESULT: A* algorithm to find out the path for the maze has been successfully implemented.
DATE: Constraints Satisfaction Problem
EXPT.NO: 07

AIM: Implementation of Constraints Satisfaction Problem.

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__"):

str = input("Enter the problem : ")


c_csp = CSP_crypt(str)

c_csp.display()

c_csp.expand(0,9,0)

c_csp.display()

if(c_csp.solved == True):
c_csp.display_ans()
OUTPUT:

RESULT: Constraint and Satisfaction problem has been successfully implemented.


Date Min - Max Algorithm
Expt.No:- 08

AIM: Implementation of minimax algorithm for an application

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 wins(state, player):


win_state = [
[state[0][0], state[0][1], state[0][2]],
[state[1][0], state[1][1], state[1][2]],
[state[2][0], state[2][1], state[2][2]],
[state[0][0], state[1][0], state[2][0]],
[state[0][1], state[1][1], state[2][1]],
[state[0][2], state[1][2], state[2][2]],
[state[0][0], state[1][1], state[2][2]],
[state[2][0], state[1][1], state[0][2]],
]
if [player, player, player] in win_state:
return True
else:
return False

def game_over(state):

return wins(state, HUMAN) or wins(state, COMP)

def empty_cells(state):

cells = []

for x, row in enumerate(state):


for y, cell in enumerate(row):
if cell == 0:
cells.append([x, y])

return cells

def valid_move(x, y):

if [x, y] in empty_cells(board):
return True
else:
return False

def set_move(x, y, player):

if valid_move(x, y):
board[x][y] = player
return True
else:
return False

def minimax(state, depth, player):


"""
AI function that choice the best move
:param state: current state of the board
:param depth: node index in the tree (0 <= depth <= 9),
but never nine in this case (see iaturn() function)
:param player: an human or a computer
:return: a list with [the best row, best col, best score]
"""
if player == COMP:
best = [-1, -1, -infinity]
else:
best = [-1, -1, +infinity]

if depth == 0 or game_over(state):
score = evaluate(state)
return [-1, -1, score]

for cell in empty_cells(state):


x, y = cell[0], cell[1]
state[x][y] = player
score = minimax(state, depth - 1, -player)
state[x][y] = 0
score[0], score[1] = x, y

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')

def render(state, c_choice, h_choice):


"""
Print the board on console
:param state: current state of the board
"""

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)

def ai_turn(c_choice, h_choice):


"""
It calls the minimax function if the depth < 9,
else it choices a random coordinate.
:param c_choice: computer's choice X or O
:param h_choice: human's choice X or O
:return:
"""
depth = len(empty_cells(board))
if depth == 0 or game_over(board):
return

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)

def human_turn(c_choice, h_choice):


"""
The Human plays choosing a valid move.
:param c_choice: computer's choice X or O
:param h_choice: human's choice X or O
:return:
"""
depth = len(empty_cells(board))
if depth == 0 or game_over(board):
return

# Dictionary of valid moves


move = -1
moves = {
1: [0, 0], 2: [0, 1], 3: [0, 2],
4: [1, 0], 5: [1, 1], 6: [1, 2],
7: [2, 0], 8: [2, 1], 9: [2, 2],
}

clean()
print(f'Human turn [{h_choice}]')
render(board, c_choice, h_choice)

while move < 1 or move > 9:


try:
move = int(input('Use numpad (1..9): '))
coord = moves[move]
can_move = set_move(coord[0], coord[1], HUMAN)

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 chooses X or O to play


while h_choice != 'O' and h_choice != 'X':
try:
print('')
h_choice = input('Choose X or O\nChosen: ').upper()
except (EOFError, KeyboardInterrupt):
print('Bye')
exit()
except (KeyError, ValueError):
print('Bad choice')

# Setting computer's choice


if h_choice == 'X':
c_choice = 'O'
else:
c_choice = 'X'

# Human may starts first


clean()
while first != 'Y' and first != 'N':
try:
first = input('First to start?[y/n]: ').upper()
except (EOFError, KeyboardInterrupt):
print('Bye')
exit()
except (KeyError, ValueError):
print('Bad choice')

# Main loop of this game


while len(empty_cells(board)) > 0 and not game_over(board):
if first == 'N':
ai_turn(c_choice, h_choice)
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

AIM: Implementation of unification and resolution for real-world problems.

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 unify(self, type_, name):


self.type = type_
self.name = name

def __eq__(self, other):


return self.name == other.name

def __str__(self):
return self.name

class Predicate:
def __init__(self, name, params):
self.name = name
self.params = params

def __eq__(self, other):


return self.name == other.name and all(a == b for a, b in zip(self.params,
other.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

def __init__(self, string):


self.sentence_index = Sentence.sentence_count
Sentence.sentence_count += 1
self.predicates = []
self.variable_map = {}
local = {}
for predicate in string.split("|"):
name = predicate[:predicate.find("(")]
params = []

for param in predicate[predicate.find("(") + 1:


predicate.find(")")].split(","):
if param[0].islower():
if param not in local: # Variable
local[param] = Parameter()
self.variable_map[local[param].name] = local[param]
new_param = local[param]
else:
new_param = Parameter(param)
self.variable_map[param] = new_param

params.append(new_param)

self.predicates.append(Predicate(name, params))

def getPredicates(self):
return [predicate.name for predicate in self.predicates]

def findPredicates(self, name):


return [predicate for predicate in self.predicates if predicate.name == name]

def removePredicate(self, predicate):


self.predicates.remove(predicate)
for key, val in self.variable_map.items():
if not val:
self.variable_map.pop(key)

def containsVariable(self):
return any(not param.isConstant() for param in self.variable_map.values())

def __eq__(self, other):


if len(self.predicates) == 1 and self.predicates[0] == other:
return True
return False

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])

def askQueries(self, queryList):


results = []

for query in queryList:


negatedQuery = Sentence(negatePredicate(query.replace(" ", "")))
negatedPredicate = negatedQuery.predicates[0]
prev_sentence_map = copy.deepcopy(self.sentence_map)
self.sentence_map[negatedPredicate.name] =
self.sentence_map.get(negatedPredicate.name, []) + [negatedQuery]
self.timeLimit = time.time() + 40

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

def resolve(self, queryStack, visited, depth=0):


if time.time() > self.timeLimit:
raise Exception
if queryStack:
query = queryStack.pop(-1)
negatedQuery = query.getNegatedPredicate()
queryPredicateName = negatedQuery.name
if queryPredicateName not in self.sentence_map:
return False
else:
queryPredicate = negatedQuery
for kb_sentence in self.sentence_map[queryPredicateName]:
if not visited[kb_sentence.sentence_index]:
for kbPredicate in
kb_sentence.findPredicates(queryPredicateName):

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

for predicate in newQueryStack:


for index, param in enumerate(predicate.params):
if param.name in substitution:
new = substitution[param.name]
predicate.params[index].unify("Variable"
if new[0].islower() else "Constant", new)

for predicate in newSentence.predicates:


newQueryStack.append(predicate)

new_visited = copy.deepcopy(visited)
if kb_sentence.containsVariable() and
len(kb_sentence.predicates) > 1:
new_visited[kb_sentence.sentence_index] = True

if self.resolve(newQueryStack, new_visited, depth + 1):


return True
return False
return True

def performUnification(queryPredicate, kbPredicate):


substitution = {}
if queryPredicate == kbPredicate:
return True, {}
else:
for query, kb in zip(queryPredicate.params, kbPredicate.params):
if query == kb:
continue
if kb.isConstant():
if not query.isConstant():
if query.name not in substitution:
substitution[query.name] = kb.name
elif substitution[query.name] != kb.name:
return False, {}
query.unify("Constant", kb.name)
else:
return False, {}
else:
if not query.isConstant():
if kb.name not in substitution:
substitution[kb.name] = query.name
elif substitution[kb.name] != query.name:
return False, {}
kb.unify("Variable", query.name)
else:
if kb.name not in substitution:
substitution[kb.name] = query.name
elif substitution[kb.name] != query.name:
return False, {}
return True, substitution

def negatePredicate(predicate):
return predicate[1:] if predicate[0] == "~" else "~" + predicate

def negateAntecedent(sentence):
antecedent = sentence[:sentence.find("=>")]
premise = []

for predicate in antecedent.split("&"):


premise.append(negatePredicate(predicate))

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

def printOutput(filename, results):


print(results)
with open(filename, "w") as file:
for line in results:
file.write(line)
file.write("\n")
file.close()

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 substituevalue(paramArray, x, y):


for index, eachVal in enumerate(paramArray):
if eachVal == x:
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(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

AIM: Implementation of block world problem .

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

def solve(self, initial_arrangement, goal_arrangement):

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 __eq__(self, other):


return (self.first_stack == other.first_stack and self.second_stack == other.second_stack
and self.total_num == other.total_num and self.moves == other.moves)

def goal_state_move(self):
while self.difference() != 0:
self = self.select_move()
return self.moves

def select_move(self): # will select and return the best move


# first try moving the top block to a stack, if the diff is not reduced, then move it to the temp_table
for index, stack in enumerate(self.first_stack):
for index2, stack2 in enumerate(self.first_stack):
if index != index2: # don't move to itself stack
curr_table, move = self.valid_state_move(self.first_stack, index, index2)
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

# 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

def valid_state_move(self, table, start_index, end_index):


temp_table = copy.deepcopy(table)
left = temp_table[start_index]
top_block = left.pop()
right = []

if end_index < 0: # move to table (-1)


temp_table.append(right)
move = (top_block, 'Table')
else: # move to stack
right = temp_table[end_index]
move = (top_block, right[-1])
right.append(top_block)

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()

initial_arrangement_1 = [["A", "B"], ["C"]]


goal_arrangement_1 = [["C", "A","B"]]

print(test_agent.solve(initial_arrangement_1, goal_arrangement_1))

if __name__ == "__main__":
test()
OUTPUT:

RESULT: Block-World problem has been successfully implemented.

You might also like