Output
Output
N
Name:Ravend Kumar Ramesh Kumar Upadhyay Roll no-19041
Practical no 1a:
Aim: Write a program to implement depth first search algorithm.
Program:
graph = {
'9' : ['3','6'],
'6' : ['8'],
'2' : [],
'4' : [],
'8' : []
visited = set()
print (node)
visited.add(node)
Output:
'9' : ['3','6'],
'6' : ['8'],
'2' : [],
'4' : [],
'8' : []
visited = []
queue = []
visited.append(node)
queue.append(node)
while queue:
m = queue.pop(0)
visited.append(neighbour)
queue.append(neighbour)
Output:
self.size = size
self.columns = []
self.columns.append(column)
def remove_in_current_row(self):
return self.columns.pop()
row = len(self.columns)
if column == queen_column:
return False
return False
for queen_row, queen_column in enumerate(self.columns):
return False
return True
def display(self):
if column == self.columns[row]:
else:
print()
def solve_queen(size):
board = QueenChessBoard(size)
number_of_solutions = 0
row = 0
column = 0
while True:
if board.is_this_column_safe_in_next_row(column):
board.place_in_next_row(column)
row += 1
column = 0
break
else:
column += 1
if row == size:
board.display()
print()
number_of_solutions += 1
board.remove_in_current_row()
row -= 1
try:
prev_column = board.remove_in_current_row()
except IndexError:
break
row -= 1
column = 1 + prev_column
n = int(input('Enter n: '))
solve_queen(n)
Output:
if height >= 1:
moveTower(height-1,fromPole,withPole,toPole)
moveDisk(fromPole,toPole)
moveTower(height-1,withPole,toPole,fromPole)
def moveDisk(fp,tp):
moveTower(3,"A","B","C")
Output:
root = 0
pruned = 0
global tree
global root
global pruned
i=0
if type(child) is list:
if depth % 2 == 1:
else:
else:
alpha = child
beta = child
pruned += 1
break
if depth == root:
global tree
global pruned
global root
if __name__ == "__main__":
if __name__ == "__main__":
alphabeta(None)
Output:
increment = 0.1
startingPoint = [1, 1]
point1 = [1,5]
point2 = [6,4]
point3 = [5,2]
point4 = [2,1]
return dist
def sumOfDistances(x1, y1, px1, py1, px2, py2, px3, py3, px4, py4):
return d1 + d2 + d3 + d4
def newDistance(x1, y1, point1, point2, point3, point4):
d1 = [x1, y1]
d1.append(d1temp)
return d1
flag = True
if d1[2] == minimum:
i=1
while flag:
d1 = newDistance(startingPoint[0]+increment, startingPoint[1],
point1, point2, point3, point4)
d2 = newDistance(startingPoint[0]-increment, startingPoint[1],
point1, point2, point3, point4)
d3 = newDistance(startingPoint[0], startingPoint[1]+increment,
point1, point2, point3, point4)
d4 = newDistance(startingPoint[0], startingPoint[1]-increment,
point1, point2, point3, point4)
minDistance = minimum
i+=1
else:
flag = False
Output:
class HelloProblem(SearchProblem):
else:
return []
for i in range(len(state))])
problem = HelloProblem(initial_state='')
result = astar(problem)
print(result.state)
print(result.path())
Output:
list1=['A','B','C','D','E','F','G','H']
list2=[1,2,3,4,5,6,0,1]
lstgraph=['A',['B',['D','E']],['C','F',['G','H']]]
startnode=lstgraph[0]
startindex=list1.index(startnode)
startcost=list2[startindex]
sgn=startcost
listpath=[]
listcost=[]
listtotalcost=[]
iter1=1
while iter1<len(lstgraph):
lsttemp=[]
lsttemp=lstgraph[iter1]
strtemp=str(lsttemp)
sgn=startcost
listp=[]
listp.append(startnode)
listc=[]
listc.append(startcost)
lenlsttemp=str(lsttemp).count(",")+1
if var1 in list1:
indx=list1.index(var1)
gn=list2[indx]
sgn=sgn+gn
listp.append(var1)
listc.append(gn)
listpath.append(listp)
listcost.append(listc)
listtotalcost.append(sgn)
iter1=iter1+1
opathcost=min(listtotalcost)
opathindex=listtotalcost.index(opathcost)
opath=listpath[opathindex]
print("Cost :",opathcost)
AOStar()
Output:
x = capacity[0]
y = capacity[1]
z = capacity[2]
memory = {}
ans = []
def get_all_states(state):
a = state[0]
b = state[1]
c = state[2]
ans.append(state)
return True
if((a,b,c) in memory):
return False
memory[(a,b,c)] = 1
if(a>0):
if(a+b<=y):
if( get_all_states((0,a+b,c)) ):
ans.append(state)
return True
else:
ans.append(state)
return True
if(a+c<=z):
if( get_all_states((0,b,a+c))):
ans.append(state)
return True
else:
ans.append(state)
return True
if(b>0):
if(a+b<=x):
return True
else:
ans.append(state)
return True
if(b+c<=z):
ans.append(state)
return True
else:
ans.append(state)
return True
if(c>0):
if(a+c<=x):
ans.append(state)
return True
else:
if( get_all_states((x, b, c-(x-a))) ):
ans.append(state)
return True
if(b+c<=y):
ans.append(state)
return True
else:
ans.append(state)
return True
return False
initial_state = (12,0,0)
print("Starting work...\n")
get_all_states(initial_state)
ans.reverse()
for i in ans:
print(i)
Output:
Program:
import os
import time
board = [' ',' ',' ',' ',' ',' ',' ',' ',' ',' ']
player = 1
Win = 1
Draw = -1
Running = 0
Stop = 1
Game = Running
Mark = 'X'
def DrawBoard():
print("___|___|___")
print("___|___|___")
print(" %c | %c | %c " % (board[7],board[8],board[9]))
print("___|___|___ ")
def CheckPosition(x):
return True
else:
return False
def CheckWin():
global Game
Game = Win
Game = Win
Game = Win
Game = Win
elif(board[2] == board[5] and board[5] == board[8] and board[2] != '
'):
Game = Win
Game=Win
Game = Win
Game=Win
elif(board[1]!=' ' and board[2]!=' ' and board[3]!=' ' and board[4]!=' '
and board[5]!=' ' and board[6]!=' ' and board[7]!=' ' and board[8]!=' '
and board[9]!=' '):
Game=Draw
else:
Game=Running
print("Tic-Tac-Toe Game")
print()
print()
print("Please Wait...")
time.sleep(1)
while(Game == Running):
os.system('cls')
DrawBoard()
if(player % 2 != 0):
Mark = 'X'
else:
Mark = 'O'
if(CheckPosition(choice)):
board[choice] = Mark
player+=1
CheckWin()
os.system('cls')
DrawBoard()
if(Game==Draw):
print("Game Draw")
elif(Game==Win):
player-=1
if(player%2!=0):
print("Player 1 Won")
else:
print("Player 2 Won")
Output:
Result: The above program to Design the simulation of tic – tac – toe
game using min-max algorithm has been executed successfully.
Practical no:6a
Aim: Write a program to solve Missionaries and Cannibals problem.
Program:
import math
class State():
self.cannibalLeft = cannibalLeft
self.missionaryLeft = missionaryLeft
self.boat = boat
self.cannibalRight = cannibalRight
self.missionaryRight = missionaryRight
self.parent = None
def is_goal(self):
return True
else:
return False
def is_valid(self):
if self.missionaryLeft >= 0 and self.missionaryRight >= 0 \
return True
else:
return False
def __hash__(self):
def successors(cur_state):
children = [];
if cur_state.boat == 'left':
new_state = State(cur_state.cannibalLeft, cur_state.missionaryLeft
- 2, 'right',
cur_state.cannibalRight, cur_state.missionaryRight + 2)
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)
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)
if new_state.is_valid():
new_state.parent = cur_state
children.append(new_state)
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)
if new_state.is_valid():
new_state.parent = cur_state
children.append(new_state)
else:
cur_state.cannibalRight, cur_state.missionaryRight - 2)
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)
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)
if new_state.is_valid():
new_state.parent = cur_state
children.append(new_state)
cur_state.cannibalRight, cur_state.missionaryRight - 1)
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)
if new_state.is_valid():
new_state.parent = cur_state
children.append(new_state)
return children
def breadth_first_search():
initial_state = State(3,3,'left',0,0)
if initial_state.is_goal():
return initial_state
frontier = list()
explored = set()
frontier.append(initial_state)
while frontier:
state = frontier.pop(0)
if state.is_goal():
return state
explored.add(state)
children = successors(state)
frontier.append(child)
return None
def print_solution(solution):
path = []
path.append(solution)
parent = solution.parent
while parent:
path.append(parent)
parent = parent.parent
for t in range(len(path)):
state = path[len(path) - t - 1]
str(state.missionaryRight) + ")")
def main():
solution = breadth_first_search()
print
("(cannibalLeft,missionaryLeft,boat,cannibalRight,missionaryRight)")
print_solution(solution)
if __name__ == "__main__":
main()
Output:
GOAL = '''1-2-3
4-5-6
7-8-e'''
INITIAL = '''4-1-2
7-e-3
8-5-6'''
def list_to_string(list_):
def string_to_list(string_):
return ir, ic
goal_positions = {}
rows_goal = string_to_list(GOAL)
class EightPuzzleProblem(SearchProblem):
rows = string_to_list(state)
actions = []
if row_e> 0:
actions.append(rows[row_e - 1][col_e])
if row_e< 2:
actions.append(rows[row_e + 1][col_e])
if col_e> 0:
actions.append(rows[row_e][col_e - 1])
if col_e< 2:
actions.append(rows[row_e][col_e + 1])
return actions
def result(self, state, action):
rows = string_to_list(state)
return list_to_string(rows)
return 1
rows = string_to_list(state)
distance = 0
return distance
result = astar(EightPuzzleProblem(INITIAL))
for action, state in result.path():
print(state)
Output:
Program:
import itertools, random
deck =
list(itertools.product(range(1,52),['Spade','Heart','Diamond','Club']))
random.shuffle(deck)
print("Cards are:")
for i in range(13):
Program:
dictpath={
'A':{'B':3,'C':1,'D':8},
'B':{'D':4},
'C':{'D':5},
'D':{'':0}
print(dictpath)
lstnode=[]
lstnode.append(nodes)
print(lstnode)
lstnn=[]
lstcc=[]
lsttc=[]
print("\n",node,"-",it1,":",path[it1])
if node == lstnode[0]:
lstn1=[]
lstc1=[]
if it1 == node1:
print(node1,"-",it2,":",path1[it2])
lstn1.append(node)
lstn1.append(node1)
lstn1.append(it2)
lstc1.append(path[it1])
lstc1.append(path1[it2])
cost=path[it1]+path1[it2]
print(lstn1)
print(lstc1)
print(cost)
lstnn.append(list(lstn1))
lstcc.append(list(lstc1))
lsttc.append(cost)
print(lstnn)
print(lstcc)
print(lsttc)
minindx=min(lsttc)
indx=lsttc.index(minindx)
Result: The above program to Solve the block of World problem has
been executed successfully.
Practical no:8b
Aim: Solve constraints satisfications problem.
Program:
from __future__ import print_function
constraints = [
print(backtrack(my_problem))
print(backtrack(my_problem,
variable_heuristic=MOST_CONSTRAINED_VARIABLE))
print(backtrack(my_problem,
variable_heuristic=HIGHEST_DEGREE_VARIABLE))
print(backtrack(my_problem,
value_heuristic=LEAST_CONSTRAINING_VALUE))
print(backtrack(my_problem,
variable_heuristic=MOST_CONSTRAINED_VARIABLE,
value_heuristic=LEAST_CONSTRAINING_VALUE))
print(backtrack(my_problem,
variable_heuristic=HIGHEST_DEGREE_VARIABLE,
value_heuristic=LEAST_CONSTRAINING_VALUE))
print(min_conflicts(my_problem))
Output:
print("(x+y)+z= ",sum1)
print("x+(y+z)= ",sum2)
sum1=int(x)*(int(y)+ int(z))
sum2=(int(x)*int(y))+(int(x)* int(z))
print("x(y+z)= ",sum1)
print("xy+xz= ",sum2)