AI
AI
Code:
while queue:
node = queue.popleft()
graph = {
'A': ['B', 'C'],
'B': ['D', 'E'],
'C': ['F'],
'D': [],
'E': ['F'],
'F': []
}
bfs(graph, 'A')
print()
print("Arriyaan Ali Syed")
Output:
Program 02: Write a program to perform Depth-First Search.
Code:
graph = {
'A': ['B', 'C'],
'B': ['D', 'E'],
'C': ['F'],
'D': [],
'E': ['F'],
'F': []
}
dfs(graph, 'A')
print()
print("Arriyaan Ali Syed")
Output:
Program 03: Write a program to perform State Space Search.
Code:
goal_state = (1, 2, 3, 4, 5, 6, 7, 8, 0)
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]
}
def bfs(start_state):
queue = deque([(start_state, [])])
visited = set()
while queue:
state, path = queue.popleft()
if state == goal_state:
return path
visited.add(state)
zero_index = state.index(0)
return None
def print_matrix(state):
print("---------")
for i in range(0, 9, 3):
print("|", state[i], state[i+1], state[i+2], "|")
print("---------")
initial_state = (1, 2, 3, 4, 0, 5, 6, 7, 8)
solution = bfs(initial_state)
if solution:
print("Solution found in", len(solution), "moves.")
print("Path to solution:")
for step in solution:
print_matrix(step)
else:
print("No solution found.")
import heapq
class Graph:
def __init__(self):
self.nodes = {}
while priority_queue:
cost, current_node = heapq.heappop(priority_queue)
if current_node in visited:
continue
print(f"Visiting: {current_node}")
visited.add(current_node)
if current_node == goal:
print("Goal reached!")
return True
graph = Graph()
graph.add_edge('A', 'B', 1)
graph.add_edge('A', 'C', 3)
graph.add_edge('B', 'D', 2)
graph.add_edge('C', 'D', 1)
graph.add_edge('D', 'E', 5)
graph.add_edge('C', 'F', 6)
Output:
Program 05: Write a program to implement A* Algorithm.
Code:
import heapq
class Graph:
def __init__(self):
self.nodes = {}
while open_list:
current_f, current_node = heapq.heappop(open_list)
if current_node == goal:
return self.reconstruct_path(came_from,
current_node)
return None
graph = Graph()
graph.add_edge('A', 'B', 1)
graph.add_edge('A', 'C', 4)
graph.add_edge('B', 'C', 2)
graph.add_edge('B', 'D', 5)
graph.add_edge('C', 'D', 1)
graph.add_edge('D', 'E', 3)
heuristic = {
'A': 7,
'B': 6,
'C': 2,
'D': 1,
'E': 0
}
Output:
INDEX
import heapq
class Graph:
def __init__(self):
self.graph = {}
self.heuristics = {}
while open_list:
_, current = heapq.heappop(open_list)
if current in closed_list:
continue
closed_list.add(current)
best_choice = None
min_cost = float('inf')
best_costs[current] = min_cost
solution.append(current)
return solution[::-1]
g = Graph()
g.add_edge('A', ['B', 'C'], 1)
g.add_edge('B', ['D', 'E'], 1)
g.add_edge('C', ['F', 'G'], 2)
g.add_edge('D', [], 1)
g.add_edge('E', [], 2)
g.add_edge('F', [], 1)
g.add_edge('G', [], 3)
g.set_heuristic('A', 5)
g.set_heuristic('B', 3)
g.set_heuristic('C', 4)
g.set_heuristic('D', 0)
g.set_heuristic('E', 0)
g.set_heuristic('F', 0)
g.set_heuristic('G', 0)
shortest_path = g.ao_star('A')
print("Shortest Path using AO*: ", shortest_path)
print("Arriyaan Ali Syed")
Output:
Program 07: Write a program to perform Min Max Algorithm.
Code:
if is_maximizing:
return max(
minimax(depth + 1, node_index * 2, False, values, max_depth),
minimax(depth + 1, node_index * 2 + 1, False, values,
max_depth)
)
else:
return min(
minimax(depth + 1, node_index * 2, True, values, max_depth),
minimax(depth + 1, node_index * 2 + 1, True, values,
max_depth)
)
if __name__ == "__main__":
# Binary tree representation of possible end game values
values = [3, 5, 6, 9, 1, 2, 0, -1] # Leaf nodes
max_depth = 3 # log2(len(values)) = 3 (3 levels deep)
optimal_value = minimax(0, 0, True, values, max_depth)
print("The values are:", values)
print("The optimal value is:", optimal_value)
print("Arriyaan Ali Syed")
Output:
Program 08: Write a program to perform Min Max Algorithm with Alpha-Beta
Pruning.
Code:
import math
if isMaximizingPlayer:
best = -math.inf
else:
best = math.inf
# Tree depth
maxDepth = int(math.log2(len(values)))
Output:
Program 09: Write a program to implement Tic-Tac-Toe.
Code:
def print_board(board):
for row in board:
print(" | ".join(row))
print("-" * 9)
return False
def is_full(board):
return all(cell != " " for row in board for cell in row)
def tic_tac_toe():
board = [[" " for _ in range(3)] for _ in range(3)]
current_player = "X"
board[row][col] = current_player
print_board(board)
if check_winner(board, current_player):
print(f"Player {current_player} wins!")
break
if is_full(board):
print("It's a draw!")
break
import sys
from itertools import permutations
start_city = 0
min_cost, best_route = travelling_salesman_problem(graph, start_city)
Output:
Program 11: Write a program to perform Hill Climbing.
Code:
import random
import math
def objective_function(x):
return -x**2 + 5*x + 10
Output:
Program 12: Use python to solve Quadratic Equation.
Code:
import math
a = 1
b = 10
c = -24
if a == 0:
print("Input correct quadratic equation")
else:
equationroots(a, b, c)
print("Arriyaan Ali Syed")
Output:
INDEX