0% found this document useful (0 votes)
27 views8 pages

Chittopadhyay 1

Uploaded by

sunnybalawat23
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views8 pages

Chittopadhyay 1

Uploaded by

sunnybalawat23
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

#PRACTICAL-1(a) dfs 'D': set(['B']),

graph1 = {'A': set(['B', 'C']), 'E': set(['B', 'F']),


'B': set(['A', 'D', 'E']), 'F': set(['C', 'E'])
'C': set(['A', 'F']), }
'D': set(['B']), print(bfs(graph, 'A'))
'E': set(['B', 'F']),
'F': set(['C', 'E']) } #PRACTICAL-2(a) n queen
def dfs(graph, node, visited): def is_Safe(board,row,col):
if node not in visited: for i in range(row):
visited.append(node) if board[i][col]==1:
for n in graph[node]: return False
dfs(graph, n, visited) for i,j in zip(range(row,-1,-1),range(col,-1,-1)):
return visited if j<0:
visited = dfs(graph1, 'A', []) break
print(visited) if board[i][j]==1:
#PRACTICAL-1(b) bfs return False
from collections import deque for i,j in zip(range(row,-1,-
1),range(col,len(board))):
def bfs(graph, start):
if j>=len(board):
visited = set()
break
queue = deque([start])
if board[i][j]==1:
visited.add(start)
return False
while queue:
return True
vertex = queue.popleft()
def solve_n_queens_util(board,row):
print(vertex, end = '')
if row>=len(board):
for neighbor in graph[vertex]:
return True
if neighbor not in visited:
for col in range(len(board)):
visited.add(neighbor)
if is_Safe(board,row,col):
queue.append(neighbor)
board[row][col]=1
if _name_ == "_main_":
if solve_n_queens_util(board,row+1):
graph = {'A': set(['B', 'C']),
return True
'B': set(['A', 'D', 'E']),
board[row][col]=0
'C': set(['A', 'F']),
return False
def solve_n_queens(n): #store solution path
board=[[0 for _ in range(n)] for _ in range(n)] ans = [ ]
if not solve_n_queens_util(board,0): def get_all_states(state):
print("solution does not exist") #let the 3 jugs be called a,b,c
return a = state[0]
for row in board: b = state[1]
print(" ".join("Q" if col else "." for col in c = state[2]
row))
if(a==6 and b==6):
solve_n_queens(4)
ans.append(state)
return True
#PRACTICAL-2(B) tower of hanoi
#if current state is already visited earlier
def moveTower(height, fromPole, toPole,
withPole): if((a,b,c) in memory):

if height>= 1: return False

moveTower(height-1, fromPole, withPole, memory[(a,b,c)] = 1


toPole) #empty jug a
moveDisk(fromPole, toPole) if(a>0):
moveTower(height-1, withPole, toPole, #empty a into b
fromPole)
if(a+b<=y):
if( get_all_states((0,a+b,c)) ):
def moveDisk(fp, tp):
ans.append(state)
print("moving disk from", fp, "to", tp)
return True
moveTower(3,"A", "B", "C")
else:
#PRACTICAL-3
if( get_all_states((a-(y-b), y, c)) ):
#3 water jugs capacity-->(x,y,z) where x>y>z
ans.append(state)
#initial state (12,0,0)
return True
#final state(6,6,0)
#empty a into c
capacity = (12,8,5)
if(a+c<=z):
#maximum capacities of 3 jugs--> x,y,z
if( get_all_states((0,b,a+c)) ):
x = capacity[0]
ans.append(state)
y = capacity[1]
return True
z = capacity[2]
else:
#to mark visited states
if( get_all_states((a-(z-c), b, z)) ):
memory = { }
3rd continue ans.append(state)

ans.append(state) return True

return True #empty c into b

#empty jug b if(b+c<=y):

if(b>0): if( get_all_states((a,b+c,0)) ):

#empty b into a ans.append(state)

if(a+b<=x): return True

if( get_all_states((a+b,0,c)) ): else:

ans.append(state) if( get_all_states((a,y,c-(y-b))) ):

return True ans.append(state)

else: return True

if( get_all_states((x, b-(x-a), c)) ): return False

ans.append(state) initial_state = (12,0,0)

return True print("Starting work...\n")

#empty b into c get_all_states(initial_state)

if(b+c<=z): ans.reverse()

if( get_all_states((a,0,b+c)) ): for i in ans:

ans.append(state) print(i)

return True
else:
if( get_all_states((a,b-(z-c),z)) ):
ans.append(state)
return True
#empty jug c
if(c>0):
#empty b into a
if(a+c<=x):
if( get_all_states((a+c,b,0)) ):
ans.append(state)
return True
else:
if( get_all_states((x,b,c-(x-a))) ):
#PRACTICAL-4 astar 'A': {'B': 1, 'C': 4},
import heapq 'B': {'A': 1, 'D': 2, 'E': 5},
def astar(graph, start, goal, heuristic): 'C': {'A': 4, 'F': 3},
open_set = [] 'D': {'B': 2},
heapq.heappush(open_set, (heuristic(start, 'E': {'B': 5, 'F': 1},
goal), start))
'F': {'C': 3, 'E': 1} }
came_from = {}
def manhattan_distance(a, b):
cost_so_far = {start: 0}
# Replace with your actual heuristic
while open_set: calculation
_, current = heapq.heappop(open_set) return abs(ord(a) - ord(b))
if current == goal: start_node = 'A'
return reconstruct_path(came_from, goal_node = 'F'
current)
path = astar(graph, start_node, goal_node,
manhattan_distance)
for neighbor in graph[current]: if path:
new_cost = cost_so_far[current] + print("Path found:", path)
graph[current][neighbor]
else:
if neighbor not in cost_so_far or
new_cost < cost_so_far[neighbor]: print("No path found.")

cost_so_far[neighbor] = new_cost
priority = new_cost +
heuristic(neighbor, goal)
heapq.heappush(open_set, (priority,
neighbor))
came_from[neighbor] = current
return None
def reconstruct_path(came_from, current):
total_path = [current]
while current in came_from:
current = came_from[current]
total_path.insert(0, current)
return total_path

# Example usage:
graph = {
#practical-5 tic tac toe elif(board[4] == board[5] and board[5] ==
board[6] and board[4] != ' '):
import os , import time
Game = Win
board = [' ',' ',' ',' ',' ',' ',' ',' ',' ',' ']
elif(board[7] == board[8] and board[8] ==
player = 1 board[9] and board[7] != ' '):
####Win Flags######### Game = Win
Win = 1 ,Draw = -1 ,Running = 0 #Vertical Winning Condition
Stop = 1 elif(board[1] == board[4] and board[4] ==
##################################### board[7] and board[1] != ' '):

Game = Running Game = Win

Mark = 'X' elif(board[2] == board[5] and board[5] ==


board[8] and board[2] != ' '):
#This Function Draws Game Board
Game = Win
def DrawBoard():
elif(board[3] == board[6] and board[6] ==
print(" %c | %c | %c " % board[9] and board[3] != ' '):
(board[1],board[2],board[3]))
Game = Win
print("_|_|_")
#Diagonal Winning Condition
print(" %c | %c | %c " %
(board[4],board[5],board[6])) elif(board[1] == board[5] and board[5] ==
board[9] and board[5] != ' '):
print("_|_|_")
Game = Win
print(" %c | %c | %c " %
(board[7],board[8],board[9])) elif(board[3] == board[5] and board[5] ==
board[7] and board[5] != ' '):
print("_|_|_")
Game = Win
#This Function Checks position is empty or not
#Match Tie or Draw Condition
def CheckPosition(x):
elif(board[1] != ' ' and board[2] != ' ' and
if(board[x] == ' '): board[3] != ' ' and board[4] != ' ' and board[5]
return True != ' ' and board[6] != ' ' and board[7] != ' ' and
board[8] != ' ' and board[9] != ' '):
else:
Game = Draw
return False
else:
#This Function Checks player has won or not
Game = Running
def CheckWin():
print("TIC_TAC-TOE GAME")
global Game
print("Player 1 [X] --- Player 2 [O]\n")
#Horizontal winning condition
print()
if(board[1] == board[2] and board[2] ==
board[3] and board[1] != ' '): print("Please Wait!.....")

Game = Win time.sleep(1)


while(Game == Running): #practical-6 shuffle deck of cards
os.system('cls') import random
DrawBoard() suits = ('Hearts', 'Diamonds', 'Spades', 'Clubs')
if(player % 2 != 0): ranks = ('Two', 'Three', 'Four', 'Five', 'Six',
'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen',
print("Player 1's chance ") 'King', 'Ace')
Mark = 'X' deck = [(rank,suit) for suit in suits for rank in
else: ranks]

print("Player 2's chance ") def shuffle_deck(deck):

Mark = 'O' random.shuffle(deck)

choice = int(input("Enter the position return deck


between [1-9] where you want to mark "))
if(CheckPosition(choice)): shuffled_deck = shuffle_deck(deck)
board[choice] = Mark for card in shuffled_deck:
player+=1 print(f'{card[0]} of {card[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")
#practical-7 ao* algo
class Graph: # Update the heuristic value of the node
self.heuristic[node] =
sum(self.heuristic.get(c, 0) for c in min_child)
def _init_(self, graph, heuristic, start_node):
# Mark node as solved and update the
self.graph = graph # AND-OR graph solution graph
(problem space)
self.status[node] = "Solved"
self.heuristic = heuristic # Heuristic values
for each node self.solution_graph[node] = min_child
self.start_node = start_node # Starting
node
def display_solution(self):
self.status = {} # Status of nodes (solved,
not solved) """Display the solution path derived by
the AO* algorithm."""
self.solution_graph = {} # Solution graph
(final solution graph) print("Solution graph:")
for node, child in
self.solution_graph.items():
def get_min_cost_child(self, node):
print(f"{node} -> {child}")
"""Get the child node with the minimum
heuristic cost.""" # Define the graph (AND-OR graph)

# The key should sum the heuristic values graph = {


of the children nodes 'A': [['B', 'C'], ['D']], # Node A has two
return min(self.graph.get(node, []), children, one is AND with (B, C), and one is D
key=lambda child: sum(self.heuristic.get(c, 0) 'B': [['E'], ['F']],
for c in child))
'C': [['G']], 'D': [['H']],
'E': [], 'F': [], 'G': [], 'H': [] }
def ao_star(self, node):
# Heuristic values for each node
"""Performs the AO algorithm
recursively.""" heuristic = { 'A': 1, 'B': 6, 'C': 2, 'D': 12, 'E': 2,

if node not in self.graph or not 'F': 4, 'G': 0, 'H': 3 }


self.graph[node]: # Starting node start_node = 'A'
return # Initialize the Graph
# Get the minimum cost child or set of g = Graph(graph, heuristic, start_node)
children (AND nodes)
# Run AO* algorithm
min_child =
self.get_min_cost_child(node) g.ao_star(start_node)
# Recursively solve the child nodes
for child in min_child: # Display the solution graph
self.ao_star(child) g.display_solution()
flag = True
#practical-8 hill climbing def newPoints(minimum, d1, d2, d3, d4):
import math if d1 [2] == minimum:
increment = 0.1 return [d1[0], d1[1]]
starting_Point = [1, 1] elif d2[2] == minimum:
point1 = [1,5] return [d2[0], d2[1]]
point2 = [6,4] elif d3[2] == minimum:
point3 = [5,2] return [d3[0], d3[1]]
point4 = [2,1] elif d4[2] == minimum:
return [d4[0], d4[1]]
def distance(x1, y1, x2, y2):
dist = math.pow(x2-x1, 2) + math.pow(y2-y1, i=1
2)
return dist
while flag:
def sumOfDistances(x1, y1, px1, py1, px2, py2,
px3, py3, px4, py4): d1 =
newDistance(starting_Point[0]+increment,
d1 = distance(x1, y1, px1, py1) starting_Point[1], point1, point2, point3,
point4)
d2 = distance(x1, y1, px2, py2)
d2 = newDistance(starting_Point[0]-
d3 = distance(x1, y1, px3, py3) increment, starting_Point[1], point1,
d4 = distance(x1, y1, px4, py4) point2,point3, point4)

return d1 + d2 + d3 + d4 d3 = newDistance(starting_Point[0],
starting_Point[1]+increment, point1, point2,
point3, point4)
def newDistance(x1, y1, point1, point2, d4 = newDistance(starting_Point[0],
point3, point4): starting_Point[1]-increment, point1, point2,
d1 = [x1, y1] point3, point4)

d1temp = sumOfDistances(x1, y1, print (i,'', round(starting_Point[0], 2),


point1[0],point1[1], point2[0],point2[1], round(starting_Point[1], 2))
point3[0],point3[1], point4[0],point4[1]) minimum = min(d1[2], d2[2], d3[2], d4[2])
d1.append(d1temp) if minimum <minDistance:
return d1 starting_Point = newPoints(minimum, d1,
d2, d3, d4)

minDistance = sumOfDistances minDistance = minimum


(starting_Point[0], starting_Point[1], else:
point1[0],point1[1], point2[0],point2[1],
point3[0],point3[1], point4[0],point4[1]) flag = False

You might also like