ai codes
ai codes
graph1={
'A':set(['B','C']),
'B':set(['A','D','E']),
'C':set(['A','F']),
'D':set(['B']),
'E':set(['B','F']),
'F':set(['C','E'])
def dfs(graph,node,visited):
visited.append(node)
for n in graph[node]:
dfs(graph,n,visited)
return visited
visited=dfs(graph1,'A',[])
print(visited)
BFS
class Graph:
def __init__(self):
self.adj_list={}
def add_edge(self,u,v):
if u in self.adj_list:
self.adj_list[u].append(v)
else:
self.adj_list[u]=[v]
if v in self.adj_list:
self.adj_list[v].append(u)
else:
self.adj_list[v]=[u]
def bfs(self,start):
visited={}
queue=deque()
visited[vertex]=False
visited[start]=True
queue.append(start)
while queue:
current=queue.popleft()
print(current,end=" ")
if not visited[neighbor]:
visited[neighbor]=True
queue.append(neighbor)
#example
g=Graph()
g.add_edge(0,1)
g.add_edge(0,2)
g.add_edge(1,2)
g.add_edge(2,0)
g.add_edge(2,3)
g.add_edge(3,3)
g.bfs(2)
BFS 2 ANOTHER
def bfs(graph,start):
visited = set()
queue=deque([start])
visited.add(start)
while queue:
vertex=queue.popleft()
print(vertex,end=' ')
visited.add(neighbor)
queue.append(neighbor)
if __name__== "__main__":
graph={
'A':['B','C'],
'B':['A','D','E'],
'C':['A','F'],
'D':['B'],
'E':['B','F'],
'F':['C','E']
bfs(graph,'A')
TOWER OF HANOI
def moveTower(height,fromPole,toPole,withPole):
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")
N QUEEN
def is_Safe(board,row,col):
for i in range(row):
if board[i][col]==1:
return False
if j<0:
break
if board[i][j]==1:
return False
if j>=len(board):
break
if board[i][j]==1:
return False
return True
def solve_n_queens_util(board,row):
if row>=len(board):
return True
if is_Safe(board,row,col):
board[row][col]=1
if solve_n_queens_util(board,row+1):
return True
board[row][col]=0
return False
def solve_n_queens(n):
if not solve_n_queens_util(board,0):
return
for row in board:
solve_n_queens(4)
JUG PROBLEM
capacity = (12, 8, 5)
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]
if (a == 6 and b == 6):
ans.append(state)
return True
if (a, b, c) in memory:
return False
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 > 0:
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:
if get_all_states((a + b, 0, c)):
ans.append(state)
return True
else:
if get_all_states((x, b - (x - a), c)):
ans.append(state)
return True
if b > 0:
if b + c <= z:
if get_all_states((a, 0, b + c)):
ans.append(state)
return True
else:
ans.append(state)
return True
if c > 0:
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))):
ans.append(state)
return True
if c > 0:
if b + c <= y:
if get_all_states((a, b + c, 0)):
ans.append(state)
return True
else:
if get_all_states((a, y, c - (y - b))):
ans.append(state)
return True
return False
# Initial state
initial_state = (12, 0, 0)
print("Starting work...\n")
get_all_states(initial_state)
ans.reverse()
for i in ans:
print(i)
A STAR ALGO
closed_set = set()
g[start_node] = 0
parents[start_node] = start_node
for v in open_set:
n=v
if n == None:
return None
if n == stop_node:
path = []
while parents[n] != n:
path.append(n)
n = parents[n]
path.append(start_node)
path.reverse()
return path
open_set.add(m)
parents[m] = n
# If the new path to the neighbor is shorter, update its cost and parent
else:
parents[m] = n
if m in closed_set:
closed_set.remove(m)
open_set.add(m)
open_set.remove(n)
closed_set.add(n)
return None
def get_neighbors(v):
if v in Graph_nodes:
return Graph_nodes[v]
else:
return None
def heuristic(n):
H_dist = {
'A': 11,
'B': 6,
'C': 5,
'D': 7,
'E': 3,
'F': 6,
'G': 5,
'H': 3,
'I': 1,
'J': 0
return H_dist[n]
Graph_nodes = {
aStarAlgo('A', 'J')
# write a python program to design the sitmulation of tic tac toe game
import os
import time
board = [' ',' ',' ',' ',' ',' ',' ',' ',' ',' '] # Initialize with spaces instead of empty strings
player = 1
win = 1
draw = -1
running = 0
stop = 1
game = running
Mark = 'X'
def Drawboard():
print("__|___|___")
print("__|___|___")
print(" | | ")
def Cheackposition(x):
return True
else:
return False
def Checkwin():
global game
game = win
game = win
game = win
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("Please Wait...")
time.sleep(1)
while(game == running):
os.system('cls')
Drawboard()
if(player % 2 != 0):
Mark = 'X'
else:
Mark = 'O'
choice = int(input("Enter the position between [1-9] where you want to mark : "))
if(Cheackposition(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")
Cards
import random
suits =['Hearts','Diamonds','Spades','Clubs']
ranks =['2','3','4','5','6','7','8','9','10','Jack','Queen','King','Ace']
def shuffle_deck(deck):
random.shuffle(deck)
return deck
shuffle_deck=shuffle_deck(deck)
print(f'{card[0]} of {card[1]}')
AO ALGO
class Graph:
return
min_child = self.get_min_cost_child(node)
self.ao_star(child)
self.solution_graph[node] = min_child
def display_solution(self):
print("Solution graph:")
graph = {
'C': [['G']],
'D': [['H']],
'E': [],
'F': [],
'G': [],
'H': []
heuristic = {
'A': 1,
'B': 6,
'C': 2,
'D': 12,
'E': 2,
'F': 4,
'G': 0,
'H': 3
}
# Starting node
start_node = 'A'
g.ao_star(start_node)
g.display_solution()
HILL Climbing
import math
increment = 0.1
starting_Point = [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
d1 = [x1, y1]
d1.append(d1temp)
return d1
flag = True
if d1 [2] == minimum:
i=1
while flag:
if minimum <minDistance:
minDistance = minimum
else:
flag = False