Lab Manual AI Lab VI Sem
Lab Manual AI Lab VI Sem
Lab Manual AI Lab VI Sem
Gurgaon
Lab Manual
# Constructor
def __init__(self):
while queue:
# Driver code
Output:
Following is Breadth First Traversal (starting from vertex 2)
>3
20313
>
class Graph:
# Constructor
def __init__(self):
# Driver code
Output:
Following is Depth First Traversal (starting from vertex 2)
20193
import numpy as np
import random
def create_board():
return(np.array([[0, 0, 0],
[0, 0, 0],
[0, 0, 0]]))
def possibilities(board):
l = []
for i in range(len(board)):
for j in range(len(board)):
if board[i][j] == 0:
l.append((i, j))
return(l)
selection = possibilities(board)
current_loc = random.choice(selection)
board[current_loc] = player
return(board)
for x in range(len(board)):
win = True
for y in range(len(board)):
if board[x, y] != player:
win = False
continue
if win == True:
return(win)
return(win)
for x in range(len(board)):
win = True
for y in range(len(board)):
if board[y][x] != player:
win = False
continue
if win == True:
return(win)
return(win)
win = True
y=0
for x in range(len(board)):
if board[x, x] != player:
win = False
if win:
return win
win = True
if win:
for x in range(len(board)):
y = len(board) - 1 - x
if board[x, y] != player:
win = False
return win
# a winner or a tie
def evaluate(board):
winner = 0
for player in [1, 2]:
if (row_win(board, player) or
col_win(board,player) or
diag_win(board,player)):
winner = player
winner = -1
return winner
def play_game():
print(board)
sleep(2)
while winner == 0:
print(board)
sleep(2)
counter += 1
winner = evaluate(board)
if winner != 0:
break
return(winner)
# Driver Code
Output:
[[0 0 0]
[0 0 0]
[0 0 0]]
Board after 1 move
[[0 0 0]
[0 0 0]
[1 0 0]]
Board after 2 move
[[0 0 0]
[0 2 0]
[1 0 0]]
Board after 3 move
[[0 1 0]
[0 2 0]
[1 0 0]]
Board after 4 move
[[0 1 0]
[2 2 0]
[1 0 0]]
Board after 5 move
[[1 1 0]
[2 2 0]
[1 0 0]]
Board after 6 move
[[1 1 0]
[2 2 0]
[1 2 0]]
Board after 7 move
[[1 1 0]
[2 2 0]
[1 2 1]]
Board after 8 move
[[1 1 0]
[2 2 2]
[1 2 1]]
Winner is: 2
class Solution:
def solve(self, board):
dict = {}
flatten = []
for i in range(len(board)):
flatten += board[i]
flatten = tuple(flatten)
dict[flatten] = 0
return 0
return self.get_paths(dict)
cnt = 0
while True:
if len(current_nodes) == 0:
return -1
next_moves = self.find_next(node)
dict[move] = cnt + 1
return cnt + 1
cnt += 1
moves = {
0: [1, 3],
1: [0, 2, 4],
2: [1, 5],
3: [0, 4, 6],
4: [1, 3, 5, 7],
5: [2, 4, 8],
6: [3, 7],
7: [4, 6, 8],
8: [5, 7],
results = []
pos_0 = node.index(0)
new_node = list(node)
results.append(tuple(new_node))
return results
ob = Solution()
matrix = [
[3, 1, 2],
[4, 7, 5],
[6, 8, 0]
]
print(ob.solve(matrix))
Input:
matrix = [
[3, 1, 2],
[4, 7, 5],
[6, 8, 0] ]
Output:
4
Output:
Steps:
00
40
43
03
30
33
42
02
V=4
vertex = []
for i in range(V):
if i != s:
vertex.append(i)
min_path = maxsize
next_permutation=permutations(vertex)
for i in next_permutation:
current_pathweight = 0
# compute current path weight
k=s
for j in i:
current_pathweight += graph[k][j]
k=j
current_pathweight += graph[k][s]
# update minimum
return min_path
# Driver Code
if __name__ == "__main__":
s=0
print(travellingSalesmanProblem(graph, s))
Output
80
7. Write a Program to Implement Tower of Hanoi using Python.
# Recursive Python function to solve tower of hanoi
if n == 1:
return
# Driver code
n=4
Output
Move disk 1 from rod A to rod B
Move disk 2 from rod A to rod C
Move disk 1 from rod B to rod C
Move disk 3 from rod A to rod B
Move disk 1 from rod C to rod A
Move disk 2 from rod C to rod B
Move disk 1 from rod A to rod B
Move disk 4 from rod A to rod C
Move disk 1 from rod B to rod C
Move disk 2 from rod B to rod A
Move disk 1 from rod C to rod A
Move disk 3 from rod B to rod C
Move disk 1 from rod A to rod B
Move disk 2 from rod A to rod C
Move disk 1 from rod B to rod C
Output:
A: [4, 3, 2, 1] B: [] C: []
class Position(Object):
def __str__(self):
return self.locname
class HasHeight(Object):
height: int
class HasPosition(Object):
at: Position
super().__init__(*args, **kwargs)
self.height = 2
owner: Monkey
attached: PalmTree
class World(Object):
locations: Set[Position]
p1 = Position()
p2 = Position()
p3 = Position()
w = World()
w.locations.add(p1)
w.locations.add(p2)
w.locations.add(p3)
m = Monkey()
m.height = 0 # ground
m.at = p1
box = Box()
box.height = 2
box.at = p2
p = PalmTree()
p.at = p3
b = Banana()
b.attached = p
assert monkey.height < 1, "Monkey can only move while on the ground"
monkey.at = where
assert monkey.height < 1, "Monkey can only move the box while on the ground"
monkey.at = where
box.at = where
monkey.height += box.height
banana.owner = monkey
banana.at = palmtree.at
return "Remembered that if banana is on palm tree, its location is where palm tree is"
def infer_banana_height(palmtree: PalmTree, banana: Banana):
banana.height = palmtree.height
return "Remembered that if banana is on the tree, its height equals tree's height"
[w,p1,p2,p3,m,box,p,b],
Result:
$ python ./monkey.py
Remembered that if banana is on the tree, its height equals tree's height
Remembered that if banana is on palm tree, its location is where palm tree is
### decorator
@classmethod
def root(cls):
return cls((3,3,1))
def get_possible_moves(self):
''' return all possible moves in the game as tuples
possible moves:
1 or 2 mis
1 or 2 cannibals
1 mis, 1 can
'''
moves = [(1, 0), (2, 0), (0, 1), (0, 2), (1, 1)]
return moves
def is_legal(self):
missionaries = self.state_vars[0]
cannibals = self.state_vars[1]
## could have done tuple unpacking too:
## missionaries, cannibals, boat = self.state_vars
## alternate
# if 0 <= missionaries <= 3 and 0 <= cannibals <= 3
# return True
###
def is_solution(self):
if self.state_vars == (0,0,0):
return True
return False
def is_failure(self):
missionaries = self.state_vars[0]
cannibals = self.state_vars[1]
boat = self.state_vars[2]
## could have done tuple unpacking too:
## missionaries, cannibals, boat = self.state_vars
def get_next_states(self):
## using possible move, get next states
moves = self.get_possible_moves()
all_states = list()
mis_right, can_right, raft_right = self.state_vars
## if raft is on right, subtract move from these numbers
## if raft is on left, add these move numbers to these numbers
for move in moves:
change_mis, change_can = move
if raft_right == 1: ## mis_right = 3; can_right = 3, raft_right = 1
new_state_vars = (mis_right-change_mis, can_right-change_can, 0)
else:
new_state_vars = (mis_right+change_mis, can_right+change_can, 1)
return all_states
def __str__(self):
return "MCState[{}]".format(self.state_vars)
def __repr__(self):
return str(self)
def search(dfs=True):
### we use the stack/queue for keeping track of where to search next
to_search = deque()
### use a list to keep track of the solutions that have been seen
solutions = list()
if possible_next_state.is_failure():
#print("Failure!")
continue
elif possible_next_state.is_solution():
## Save it into our solutions list
solutions.append(possible_next_state)
#print("Solution!")
continue
#### IMPORTANT
## which side we append on changes how the search works
## why is this?
if dfs:
to_search.append(possible_next_state)
else:
to_search.appendleft(possible_next_state)
# now that we have "seen" the state, we add the state vars to the set.
# this means next time when we do the "not in", that will return False
# because it IS in
#seen_states.add(possible_state_vars)
seen_states.add(possible_state_vars)
sol_dfs = search(True)
sol_bfs = search(False)
current_state = sol_dfs[0]
while current_state:
print(current_state)
current_state = current_state.parent
print("--")
current_state = sol_dfs[1]
while current_state:
print(current_state)
current_state = current_state.parent
print("--")
current_state = sol_bfs[0]
while current_state:
print(current_state)
current_state = current_state.parent
print("--")
current_state = sol_bfs[1]
while current_state:
print(current_state)
current_state = current_state.parent
Found 2 solutions
Found 2 solutions
MCState[(0, 0, 0)]
MCState[(1, 1, 1)]
MCState[(0, 1, 0)]
MCState[(0, 3, 1)]
MCState[(0, 2, 0)]
MCState[(2, 2, 1)]
MCState[(1, 1, 0)]
MCState[(3, 1, 1)]
MCState[(3, 0, 0)]
MCState[(3, 2, 1)]
MCState[(3, 1, 0)]
MCState[(3, 3, 1)]
--
MCState[(0, 0, 0)]
MCState[(0, 2, 1)]
MCState[(0, 1, 0)]
MCState[(0, 3, 1)]
MCState[(0, 2, 0)]
MCState[(2, 2, 1)]
MCState[(1, 1, 0)]
MCState[(3, 1, 1)]
MCState[(3, 0, 0)]
MCState[(3, 2, 1)]
MCState[(3, 1, 0)]
MCState[(3, 3, 1)]
--
MCState[(0, 0, 0)]
MCState[(0, 2, 1)]
MCState[(0, 1, 0)]
MCState[(0, 3, 1)]
MCState[(0, 2, 0)]
MCState[(2, 2, 1)]
MCState[(1, 1, 0)]
MCState[(3, 1, 1)]
MCState[(3, 0, 0)]
MCState[(3, 2, 1)]
MCState[(2, 2, 0)]
MCState[(3, 3, 1)]
--
MCState[(0, 0, 0)]
MCState[(1, 1, 1)]
MCState[(0, 1, 0)]
MCState[(0, 3, 1)]
MCState[(0, 2, 0)]
MCState[(2, 2, 1)]
MCState[(1, 1, 0)]
MCState[(3, 1, 1)]
MCState[(3, 0, 0)]
MCState[(3, 2, 1)]
MCState[(2, 2, 0)]
MCState[(3, 3, 1)]
global N
N=4
def printSolution(board):
for i in range(N):
for j in range(N):
print board[i][j],
print
return True
if isSafe(board, i, col):
# Place this queen in board[i][col]
board[i][col] = 1
# recur to place rest of the queens
if solveNQUtil(board, col + 1) == True:
return True
if solveNQUtil(board, 0) == False:
print "Solution does not exist"
return False
printSolution(board)
return True
Output:
0010
1000
0001
0100