AI - PracticalYeshi Dorjee (UE178116)
AI - PracticalYeshi Dorjee (UE178116)
AI - PracticalYeshi Dorjee (UE178116)
print("JUG1\tJUG2")
pour(0, 0)
Output:
2.Write a program to implement missionaries and carriable problem using
DFS algo.
Code:
class State():
def __init__(self, cannibalLeft, missionaryLeft, boat, cannibalRight, missionaryRight, action):
self.cannibalLeft = cannibalLeft
self.missionaryLeft = missionaryLeft
self.boat = boat
self.cannibalRight = cannibalRight
self.missionaryRight = missionaryRight
self.action = action
self.parent = None
def is_goal(self):
if self.cannibalLeft == 0 and self.missionaryLeft == 0:
return True
else:
return False
def is_valid(self):
if self.missionaryLeft >= 0 and self.missionaryRight >= 0 \
and self.cannibalLeft >= 0 and self.cannibalRight >= 0 \
and (self.missionaryLeft == 0 or self.missionaryLeft >= self.cannibalLeft) \
and (self.missionaryRight == 0 or self.missionaryRight >= self.cannibalRight):
return True
else:
return False
def __hash__(self):
return hash((self.cannibalLeft, self.missionaryLeft, self.boat, self.cannibalRight,
self.missionaryRight))
def successors(cur_state):
children = list()
if cur_state.boat == 'left':
new_state = State(cur_state.cannibalLeft, cur_state.missionaryLeft - 2, 'right',
cur_state.cannibalRight, cur_state.missionaryRight + 2,
"send two missionaries from left to right")
if new_state.is_valid():
new_state.parent = cur_state
children.append(new_state)
new_state = State(cur_state.cannibalLeft - 2, cur_state.missionaryLeft, 'right',
cur_state.cannibalRight + 2, cur_state.missionaryRight,
"send two cannibals from left to right")
if new_state.is_valid():
new_state.parent = cur_state
children.append(new_state)
new_state = State(cur_state.cannibalLeft - 1, cur_state.missionaryLeft - 1, 'right',
cur_state.cannibalRight + 1, cur_state.missionaryRight + 1,
"send one missionary and one cannibal from left to right")
if new_state.is_valid():
new_state.parent = cur_state
children.append(new_state)
new_state = State(cur_state.cannibalLeft, cur_state.missionaryLeft - 1, 'right',
cur_state.cannibalRight, cur_state.missionaryRight + 1,
"send one missionary from left to right")
if new_state.is_valid():
new_state.parent = cur_state
children.append(new_state)
new_state = State(cur_state.cannibalLeft - 1, cur_state.missionaryLeft, 'right',
cur_state.cannibalRight + 1, cur_state.missionaryRight,
"send one cannibal from left to right")
if new_state.is_valid():
new_state.parent = cur_state
children.append(new_state)
else:
new_state = State(cur_state.cannibalLeft, cur_state.missionaryLeft + 2, 'left',
cur_state.cannibalRight, cur_state.missionaryRight - 2,
"send two missionaries from right to left")
if new_state.is_valid():
new_state.parent = cur_state
children.append(new_state)
new_state = State(cur_state.cannibalLeft + 2, cur_state.missionaryLeft, 'left',
cur_state.cannibalRight - 2, cur_state.missionaryRight,
"send two cannibals from right to left")
if new_state.is_valid():
new_state.parent = cur_state
children.append(new_state)
new_state = State(cur_state.cannibalLeft + 1, cur_state.missionaryLeft + 1, 'left',
cur_state.cannibalRight - 1, cur_state.missionaryRight - 1,
"send one missionary and one cannibal from right to left")
if new_state.is_valid():
new_state.parent = cur_state
children.append(new_state)
new_state = State(cur_state.cannibalLeft, cur_state.missionaryLeft + 1, 'left',
cur_state.cannibalRight, cur_state.missionaryRight - 1,
"send one missionary from right to left")
if new_state.is_valid():
new_state.parent = cur_state
children.append(new_state)
new_state = State(cur_state.cannibalLeft + 1, cur_state.missionaryLeft, 'left',
cur_state.cannibalRight - 1, cur_state.missionaryRight,
"send one cannibal from right to left")
if new_state.is_valid():
new_state.parent = cur_state
children.append(new_state)
return children
def print_solution(solution):
path = list()
path.append(solution)
parent = solution.parent
while parent:
path.append(parent)
parent = parent.parent
def main():
initial_state = State(3, 3, 'left', 0, 0, "no action yet")
solution = iterative_deepening_depth_first_search(initial_state, 11)
print("Format: <cannibal left,missionary left,boat position,cannibal right,missionary right>")
print_solution(solution)
if __name__ == "__main__":
main()
Output:
3.Write a program for Tic-Tac-Toe game for 2 players, X (odd turn) and O
(even turn).
Code:
l=[[3,2,2],[2,2,2],[2,2,2]]
def player2():
x=int(input("Enter the row where you want to place 'o'"))
y=int(input("Enter the column where you want to place 'o'"))
l[x][y]=5
def player1():
x=int(input("Enter the row where you want to place 'x'"))
y=int(input("Enter the column where you want to place 'x'"))
l[x][y]=3
def wincheck():
prod=1
flag=0
for i in range(3):
for j in range(3):
prod=prod*l[i][j]
if prod==27:
print("player 1 wins")
flag=1
break
if prod==125:
print("player 2 wins")
flag=1
break
prod=1
for i in range(3):
for j in range(3):
prod=prod*l[j][i]
if prod==27:
flag=1
print("player 1 wins")
break
if prod==125:
flag=1
print("player 2 wins")
break
if 1*l[0][0]*l[1][1]*l[2][2]==27 or 1*l[0][2]*l[1][1]*l[2][0]==27:
flag=1
print("player 1 wins")
if 1*l[0][0]*l[1][1]*l[2][2]==125 or 1*l[0][2]*l[1][1]*l[2][0]==125:
flag=1
print("player 2 wins")
return flag
def display():
for i in range(3):
for j in range(3):
if l[i][j]==5:
print("o |",end=" ")
elif l[i][j]==3:
print("x |",end=" ")
elif l[i][j]==2:
print(" |",end=" ")
print("\n")
display()
for i in range(8):
if i%2==0:
player2()
else:
player1()
display()
if wincheck()==1:
break
if wincheck()==0:
print("it's a tie")
Output:
4.Write a program to solve the 8-queen problem by using A*as best first search
algo.
Code:
global N
N=8
def printSolution(board):
for i in range(N):
for j in range(N):
print (board[i][j],end=" ")
print("\n")
for i in range(col):
if board[row][i] == 1:
return False
for i, j in zip(range(row, -1, -1), range(col, -1, -1)):
if board[i][j] == 1:
return False
for i, j in zip(range(row, N, 1), range(col, -1, -1)):
if board[i][j] == 1:
return False
return True
def solveNQ():
board = [ [0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0]]
if solveNQUtil(board, 0) == False:
print ("Solution does not exist")
return False
printSolution(board)
return True
solveNQ()
Output:
5. Write a program to implement 8-puzzle problem using A* algo .
Code:
from copy import deepcopy
DIRECTIONS = {"U": [-1, 0], "D": [ 1, 0], "L": [ 0,-1], "R" : [ 0, 1]}
END = [[1,2,3],[4,5,6],[7,8,0]]
class Node:
def __init__(self, state, previous, g, h, dir):
self.state = state
self.previous = previous
self.g = g
self.h = h
self.dir = dir
def f(self):
return self.g + self.h
def euclidianCost(a,b):
cost = 0
for row in range(len(a)):
for col in range(len(a[0])):
pos = getPos(b,a[row][col])
cost += abs(row - pos[0]) + abs(col - pos[1])
return cost
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
def getPos(state,elem):
for row in range(len(state)):
if elem in state[row]:
return (row,state[row].index(elem))
def getAdjNode(node):
listNode = []
emptyPos= getPos(node.state,0)
for dir in DIRECTIONS.keys():
newPos = (emptyPos[0] + DIRECTIONS[dir][0], emptyPos[1] + DIRECTIONS[dir][1])
if 0 <= newPos[0] < len(node.state) and 0 <= newPos[1] < len(node.state[0]) :
newState = deepcopy(node.state)
newState[emptyPos[0]][emptyPos[1]] = node.state[newPos[0]][newPos[1]]
newState[newPos[0]][newPos[1]] = 0
listNode += [Node(newState, node.state, node.g + 1, euclidianCost(newState, END), dir)]
return listNode
def buildPath(closedSet):
node = closedSet[str(END)]
path = ""
while node.dir:
path = node.dir + path
node = closedSet[str(node.previous)]
return path
def checkio(puzzle):
openSet = {str(puzzle) : Node(puzzle,puzzle,0,euclidianCost(puzzle,END), "")}
closedSet = {}
while len(openSet) > 0:
examNode = getBestNode(openSet)
closedSet[str(examNode.state)] = examNode
if examNode.state == END:
return buildPath(closedSet)
adj = getAdjNode(examNode)
for node in adj:
if str(node.state) in closedSet.keys() or str(node.state) in openSet.keys() and
openSet[str(node.state)].f() < node.f():
continue
openSet[str(node.state)] = node
del openSet[str(examNode.state)]
return ""
if __name__ == '__main__':
print(checkio([[1, 2, 3],
[4, 6, 8],
[7, 5, 0]]))
Output:
6.Write a program which implement Tic-Tac-Toe using MinMax algo.
Code:
import time
class Game:
def __init__(self):
self.initialize_game()
def initialize_game(self):
self.current_state = [['.','.','.'],
['.','.','.'],
['.','.','.']]
self.player_turn = 'X'
def draw_board(self):
for i in range(0, 3):
for j in range(0, 3):
print('{}|'.format(self.current_state[i][j]), end=" ")
print()
print()
def is_valid(self, px, py):
if px < 0 or px > 2 or py < 0 or py > 2:
return False
elif self.current_state[px][py] != '.':
return False
else:
return True
def is_end(self):
for i in range(0, 3):
if (self.current_state[0][i] != '.' and
self.current_state[0][i] == self.current_state[1][i] and
self.current_state[1][i] == self.current_state[2][i]):
return self.current_state[0][i]
for i in range(0, 3):
if (self.current_state[i] == ['X', 'X', 'X']):
return 'X'
elif (self.current_state[i] == ['O', 'O', 'O']):
return 'O'
if (self.current_state[0][0] != '.' and
self.current_state[0][0] == self.current_state[1][1] and
self.current_state[0][0] == self.current_state[2][2]):
return self.current_state[0][0]
if (self.current_state[0][2] != '.' and
self.current_state[0][2] == self.current_state[1][1] and
self.current_state[0][2] == self.current_state[2][0]):
return self.current_state[0][2]
for i in range(0, 3):
for j in range(0, 3):
if (self.current_state[i][j] == '.'):
return None
return '.'
def max(self):
maxv = -2
px = None
py = None
result = self.is_end()
if result == 'X':
return (-1, 0, 0)
elif result == 'O':
return (1, 0, 0)
elif result == '.':
return (0, 0, 0)
for i in range(0, 3):
for j in range(0, 3):
if self.current_state[i][j] == '.':
self.current_state[i][j] = 'O'
(m, min_i, min_j) = self.min()
if m > maxv:
maxv = m
px = i
py = j
self.current_state[i][j] = '.'
return (maxv, px, py)
def min(self):
minv = 2
qx = None
qy = None
result = self.is_end()
if result == 'X':
return (-1, 0, 0)
elif result == 'O':
return (1, 0, 0)
elif result == '.':
return (0, 0, 0)
for i in range(0, 3):
for j in range(0, 3):
if self.current_state[i][j] == '.':
self.current_state[i][j] = 'X'
(m, max_i, max_j) = self.max()
if m < minv:
minv = m
qx = i
qy = j
self.current_state[i][j] = '.'
Output:
7.Write a program to solve the block world problem using ascent hill
climbing algo.
Code:
import random
import string
def generate_random_solution(length=13):
return [random.choice(string.printable) for _ in range(length)]
def evaluate(solution):
target = list("Hello, World!")
diff = 0
for i in range(len(target)):
s = solution[i]
t = target[i]
diff += abs(ord(s) - ord(t))
return diff
def mutate_solution(solution):
index = random.randint(0, len(solution) - 1)
solution[index] = random.choice(string.printable)
best = generate_random_solution()
best_score = evaluate(best)
while True:
print('Best score so far', best_score, 'Solution', "".join(best))
if best_score == 0:
break
new_solution = list(best)
mutate_solution(new_solution)
score = evaluate(new_solution)
if evaluate(new_solution) < best_score:
best = new_solution
best_score = score
Output:
9. Write a program for Mean-End Analysis by taking any current state and
implement goal state.
Code
def gps(initial_states, goal_states, operators):
prefix = 'Executing '
for operator in operators:
operator['add'].append(prefix + operator['action'])
final_states = achieve_all(initial_states, operators, goal_states, [])
if not final_states:
return None
return [state for state in final_states if state.startswith(prefix)]
def achieve_all(states, ops, goals, goal_stack):
for goal in goals:
states = achieve(states, ops, goal, goal_stack)
if not states:
return None
for goal in goals:
if goal not in states:
return None
return states
def achieve(states, operators, goal, goal_stack):
debug(len(goal_stack), 'Achieving: %s' % goal)
if goal in states:
return states
if goal in goal_stack:
return None
for op in operators:
if goal not in op['add']:
continue
result = apply_operator(op, states, operators, goal, goal_stack)
if result:
return result
def apply_operator(operator, states, ops, goal, goal_stack):
debug(len(goal_stack), 'Consider: %s' % operator['action'])
result = achieve_all(states, ops, operator['preconds'], [goal] + goal_stack)
if not result:
return None
debug(len(goal_stack), 'Action: %s' % operator['action'])
add_list, delete_list = operator['add'], operator['delete']
return [state for state in result if state not in delete_list] + add_list
import logging
def debug(level, msg):
logging.debug(' %s %s' % (level * ' ', msg))
problem = {
"start": ["space on a", "a on b", "b on c", "c on table", "space on table"],
"finish": ["space on c", "c on b", "b on a", "a on table", "space on table"],
"ops": [
{
"action": "move a from b to c",
"preconds": [
"space on a",
"space on c",
"a on b"
],
"add": [
"a on c",
"space on b"
],
"delete": [
"a on b",
"space on c"
]
},
{
"action": "move a from table to b",
"preconds": [
"space on a",
"space on b",
"a on table"
],
"add": [
"a on b"
],
"delete": [
"a on table",
"space on b"
]
},
{
"action": "move a from b to table",
"preconds": [
"space on a",
"space on table",
"a on b"
],
"add": [
"a on table",
"space on b"
],
"delete": [
"a on b"
]
},
{
"action": "move a from c to b",
"preconds": [
"space on a",
"space on b",
"a on c"
],
"add": [
"a on b",
"space on c"
],
"delete": [
"a on c",
"space on b"
]
},
{
"action": "move a from table to c",
"preconds": [
"space on a",
"space on c",
"a on table"
],
"add": [
"a on c"
],
"delete": [
"a on table",
"space on c"
]
},
{
"action": "move a from c to table",
"preconds": [
"space on a",
"space on table",
"a on c"
],
"add": [
"a on table",
"space on c"
],
"delete": [
"a on c"
]
},
{
"action": "move b from a to c",
"preconds": [
"space on b",
"space on c",
"b on a"
],
"add": [
"b on c",
"space on a"
],
"delete": [
"b on a",
"space on c"
]
},
{
"action": "move b from table to a",
"preconds": [
"space on b",
"space on a",
"b on table"
],
"add": [
"b on a"
],
"delete": [
"b on table",
"space on a"
]
},
{
"action": "move b from a to table",
"preconds": [
"space on b",
"space on table",
"b on a"
],
"add": [
"b on table",
"space on a"
],
"delete": [
"b on a"
]
},
{
"action": "move b from c to a",
"preconds": [
"space on b",
"space on a",
"b on c"
],
"add": [
"b on a",
"space on c"
],
"delete": [
"b on c",
"space on a"
]
},
{
"action": "move b from table to c",
"preconds": [
"space on b",
"space on c",
"b on table"
],
"add": [
"b on c"
],
"delete": [
"b on table",
"space on c"
]
},
{
"action": "move b from c to table",
"preconds": [
"space on b",
"space on table",
"b on c"
],
"add": [
"b on table",
"space on c"
],
"delete": [
"b on c"
]
},
{
"action": "move c from a to b",
"preconds": [
"space on c",
"space on b",
"c on a"
],
"add": [
"c on b",
"space on a"
],
"delete": [
"c on a",
"space on b"
]
},
{
"action": "move c from table to a",
"preconds": [
"space on c",
"space on a",
"c on table"
],
"add": [
"c on a"
],
"delete": [
"c on table",
"space on a"
]
},
{
"action": "move c from a to table",
"preconds": [
"space on c",
"space on table",
"c on a"
],
"add": [
"c on table",
"space on a"
],
"delete": [
"c on a"
]
},
{
"action": "move c from b to a",
"preconds": [
"space on c",
"space on a",
"c on b"
],
"add": [
"c on a",
"space on b"
],
"delete": [
"c on b",
"space on a"
]
},
{
"action": "move c from table to b",
"preconds": [
"space on c",
"space on b",
"c on table"
],
"add": [
"c on b"
],
"delete": [
"c on table",
"space on b"
]
},
{
"action": "move c from b to table",
"preconds": [
"space on c",
"space on table",
"c on b"
],
"add": [
"c on table",
"space on b"
],
"delete": [
"c on b"
]
}
]
}
def main():
start = problem['start']
finish = problem['finish']
ops = problem['ops']
for action in gps(start, finish, ops):
print(action)
if __name__ == '__main__':
main()
Output:
10. Write a program that demonstrate the working of alpha beta pruning by
taking an input of elements.
Code:
maximum = 1000000
minimum = -1000000
if(maxpl==True):
ans = minimum
for i in range(0,2):
val = alphabeta(a,b,d+1,index*2+i,False,A)
ans = max(ans, val)
a = max(a, ans)
if (b <= a):
break
return ans
else:
ans = maximum
for i in range(0,2):
val = alphabeta(a,b,d+1,index*2+i,True,A)
ans = min(ans, val)
a = min(a, ans)
if (b <= a):
break
return ans
if __name__ == "__main__":
A = [3, 5, 6, 9, 1, 2, 0, -1]
print(alphabeta(minimum,maximum,0,0,True,A))
Output:
11. Write a program to solve the Cryptographic puzzle by considering an
example SEND+MORE = MONEY
Code:
import itertools
def get_value(word, substitution):
s=0
factor = 1
for letter in reversed(word):
s += factor * substitution[letter]
factor *= 10
return s
def solve2(equation):
left, right = equation.lower().replace(' ', '').split('=')
left = left.split('+')
letters = set(right)
for word in left:
for letter in word:
letters.add(letter)
letters = list(letters)
digits = range(10)
for perm in itertools.permutations(digits, len(letters)):
sol = dict(zip(letters, perm))
if sum(get_value(word, sol) for word in left) == get_value(right, sol):
print(' + '.join(str(get_value(word, sol)) for word in left) + " = {} (mapping:
{})".format(get_value(right, sol), sol))
if __name__ == '__main__':
solve2('SEND + MORE = MONEY')
Output:
12. Write a program that derives forward chaining by using the given known
facts to prove that tomy is black. If the facts are :- Tomy barks
Tomy eats bone
Code:
nferred = []
agenda = []
def inputKB():
userInput = ""
i=0
k=0
knowledgeBase = []
while userInput != "exit":
print("Please input knowledge base:(type 'exit' if you want to stop)")
userInput = input()
if userInput != "exit":
if len(userInput) == 1:
print("Agenda[" + str(k) + "]:" + userInput[0])
agenda.insert(0,userInput)
k+=1
else:
userConclusion = userInput.split("=>")
conclusion = (userConclusion[-1])
userPremise = userConclusion[0].split("^")
premise = userPremise
count = len(premise)
newKB = [premise, conclusion, count]
knowledgeBase.append(newKB)
for j in range(0, len(premise)):
print("KB[" + str(i) + "]." + "premise[" + str(j) + "]:" + premise[j] + ", ", end = '')
print("KB[" + str(i) + "]." + "conclusion:" + conclusion + ", count:" + str(count))
i+=1
else:
print("stopped")
return knowledgeBase
def forwardChaining(knowledgeBase):
print("What is your query?")
q = input()
print("=============")
print("Forward chaining algorithm starts")
print("=============")
while agenda:
p = agenda.pop(0)
print("***** Current agenda:" + p + " *****")
if p == q:
print("Goal Achieved")
print("The query " + p + " is true based on the knowledge.")
print("---- The End -----")
return True
if p not in inferred:
inferred.append(p)
for clauseNum in range(0, len(knowledgeBase)):
for premiseNum in range (0, len(knowledgeBase[clauseNum][0])):
if p == knowledgeBase[clauseNum][0][premiseNum]: