0% found this document useful (0 votes)
2 views

AI

The document contains ten different programs demonstrating various search algorithms and game implementations, including Breadth-First Search, Depth-First Search, State Space Search, Best First Search, A* Algorithm, AO* Algorithm, Min Max Algorithm, Min Max with Alpha-Beta Pruning, Tic-Tac-Toe, and the Travelling Salesman Problem. Each program includes code snippets and outputs, showcasing the functionality of the respective algorithms. The author of all programs is Arriyaan Ali Syed.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

AI

The document contains ten different programs demonstrating various search algorithms and game implementations, including Breadth-First Search, Depth-First Search, State Space Search, Best First Search, A* Algorithm, AO* Algorithm, Min Max Algorithm, Min Max with Alpha-Beta Pruning, Tic-Tac-Toe, and the Travelling Salesman Problem. Each program includes code snippets and outputs, showcasing the functionality of the respective algorithms. The author of all programs is Arriyaan Ali Syed.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 23

Program 01: Write a program to perform Breadth-First Search.

Code:

from collections import deque

def bfs(graph, start_node):


visited = set()
queue = deque([start_node])

while queue:
node = queue.popleft()

if node not in visited:


print(node, end=" ")
visited.add(node)

for neighbor in graph[node]:


if neighbor not in visited:
queue.append(neighbor)

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:

def dfs(graph, node, visited=set()):


if node not in visited:
print(node, end=" ")
visited.add(node)

for neighbor in graph[node]:


dfs(graph, neighbor, visited)

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:

from collections import deque

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 swap(state, i, j):


state = list(state)
state[i], state[j] = state[j], state[i]
return tuple(state)

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)

for move in moves[zero_index]:


new_state = swap(state, zero_index, move)
if new_state not in visited:
queue.append((new_state, path + [new_state]))

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.")

print("Arriyaan Ali Syed")


Output:
Program 04: Write a program to perform Best First Search.
Code:

import heapq

class Graph:
def __init__(self):
self.nodes = {}

def add_edge(self, from_node, to_node, cost):


if from_node not in self.nodes:
self.nodes[from_node] = []
if to_node not in self.nodes:
self.nodes[to_node] = []
self.nodes[from_node].append((to_node, cost))

def best_first_search(self, start, goal):


visited = set()
priority_queue = []
heapq.heappush(priority_queue, (0, start)) # (heuristic,
node)

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

for neighbor, heuristic in self.nodes[current_node]:


if neighbor not in visited:
heapq.heappush(priority_queue, (heuristic,
neighbor))

print("Goal not reachable.")


return False

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)

print("Best First Search:")


graph.best_first_search('A', 'E')
print("Arriyaan Ali Syed")

Output:
Program 05: Write a program to implement A* Algorithm.
Code:

import heapq

class Graph:
def __init__(self):
self.nodes = {}

def add_edge(self, from_node, to_node, cost):


if from_node not in self.nodes:
self.nodes[from_node] = []
if to_node not in self.nodes:
self.nodes[to_node] = []
self.nodes[from_node].append((to_node, cost))
self.nodes[to_node].append((from_node, cost))

def a_star_search(self, start, goal, heuristic):


open_list = []
heapq.heappush(open_list, (0, start))
came_from = {}
g_score = {node: float('inf') for node in self.nodes}
g_score[start] = 0
f_score = {node: float('inf') for node in self.nodes}
f_score[start] = heuristic[start]

while open_list:
current_f, current_node = heapq.heappop(open_list)

if current_node == goal:
return self.reconstruct_path(came_from,
current_node)

for neighbor, cost in self.nodes[current_node]:


tentative_g_score = g_score[current_node] + cost

if tentative_g_score < g_score[neighbor]:


came_from[neighbor] = current_node
g_score[neighbor] = tentative_g_score
f_score[neighbor] = tentative_g_score +
heuristic[neighbor]
heapq.heappush(open_list, (f_score[neighbor],
neighbor))

return None

def reconstruct_path(self, came_from, current):


path = [current]
while current in came_from:
current = came_from[current]
path.append(current)
path.reverse()
return path

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
}

print("A* Search Path:")


path = graph.a_star_search('A', 'E', heuristic)
print(path)
print("Arriyaan Ali Syed")

Output:
INDEX

S.NO Name of Program Page Date of Date of Sign/


. No. Execution Submissio Remarks
n
Program 06: Write a program to implement AO* Algorithm.
Code:

import heapq

class Graph:
def __init__(self):
self.graph = {}
self.heuristics = {}

def add_edge(self, parent, children, cost):


if parent not in self.graph:
self.graph[parent] = []
self.graph[parent].append((children, cost))

def set_heuristic(self, node, h_value):


self.heuristics[node] = h_value

def get_neighbors(self, node):


return self.graph.get(node, [])

def get_heuristic(self, node):


return self.heuristics.get(node, float('inf'))

def ao_star(self, start):


open_list = [(self.get_heuristic(start), start)]
closed_list = set()
best_costs = {start: self.get_heuristic(start)}
parents = {start: None}
solution = []

while open_list:
_, current = heapq.heappop(open_list)
if current in closed_list:
continue

closed_list.add(current)

if current not in self.graph:


solution.append(current)
continue

best_choice = None
min_cost = float('inf')

for children, cost in self.get_neighbors(current):


total_cost = cost + sum(self.get_heuristic(child) for
child in children)

if total_cost < min_cost:


min_cost = total_cost
best_choice = children

for child in children:


parents[child] = current
heapq.heappush(open_list, (self.get_heuristic(child),
child))

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:

def minimax(depth, node_index, is_maximizing, values, max_depth):


# Base case: leaf node is reached
if depth == max_depth:
return values[node_index]

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:

print("Minimax Algorithm with Alpha-Beta Pruning")

import math

def minimax(depth, nodeIndex, isMaximizingPlayer, values, alpha, beta,


maxDepth):
# Base case: return leaf node value
if depth == maxDepth:
return values[nodeIndex]

if isMaximizingPlayer:
best = -math.inf

# Recur for left and right children


for i in range(2):
val = minimax(depth + 1, nodeIndex * 2 + i, False, values,
alpha, beta, maxDepth)
best = max(best, val)
alpha = max(alpha, best)

# Alpha Beta Pruning


if beta <= alpha:
break
return best

else:
best = math.inf

# Recur for left and right children


for i in range(2):
val = minimax(depth + 1, nodeIndex * 2 + i, True, values,
alpha, beta, maxDepth)
best = min(best, val)
beta = min(beta, best)

# Alpha Beta Pruning


if beta <= alpha:
break
return best

# Example leaf node values (simulated game outcomes)


values = [3, 5, 6, 9, 1, 2, 0, -1]

# Tree depth
maxDepth = int(math.log2(len(values)))

# Start the algorithm


optimal_value = minimax(0, 0, True, values, -math.inf, math.inf,
maxDepth)

print("Leaf node values:", values)


print("The optimal value is:", optimal_value)
print("Arriyaan Ali Syed")

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)

def check_winner(board, player):


# Check rows, columns, and diagonals
for row in board:
if all(cell == player for cell in row):
return True

for col in range(3):


if all(board[row][col] == player for row in range(3)):
return True

if all(board[i][i] == player for i in range(3)) or \


all(board[i][2 - i] == player for i in range(3)):
return True

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"

print("Arriyaan Ali Syed")


print("Welcome to Tic-Tac-Toe!")
print_board(board)
while True:
try:
row = int(input(f"Player {current_player}, enter row (0-2):
"))
col = int(input(f"Player {current_player}, enter column (0-
2): "))

if row < 0 or row > 2 or col < 0 or col > 2:


print("Invalid input. Row and column must be between 0
and 2.")
continue

if board[row][col] != " ":


print("That cell is already taken. Try again.")
continue

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

current_player = "O" if current_player == "X" else "X"


except ValueError:
print("Please enter a valid number.")

# Run the game


tic_tac_toe()
Output:
Program 10: Write a program to implement Travelling Salesman
Problem (TSP).
Code:

import sys
from itertools import permutations

def travelling_salesman_problem(graph, start):


# Number of cities
num_cities = len(graph)

# Store all cities except the start city


cities = [i for i in range(num_cities) if i != start]

# Initialize the minimum cost


min_path = sys.maxsize
best_route = []

# Generate all possible permutations of the cities


for perm in permutations(cities):
current_cost = 0
k = start

# Calculate the path cost


for j in perm:
current_cost += graph[k][j]
k = j

# Add the return path cost to the start city


current_cost += graph[k][start]

# Update the minimum cost and best route


if current_cost < min_path:
min_path = current_cost
best_route = [start] + list(perm) + [start]

return min_path, best_route

# Example graph represented as an adjacency matrix


graph = [
[0, 10, 15, 20],
[10, 0, 35, 25],
[15, 35, 0, 30],
[20, 25, 30, 0]
]

start_city = 0
min_cost, best_route = travelling_salesman_problem(graph, start_city)

print(f"Minimum cost: {min_cost}")


print(f"Best route: {best_route}")
print("Arriyaan Ali Syed")

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

def hill_climbing(initial_position, step_size, max_iter):


current_position = initial_position
for _ in range(max_iter):
current_value = objective_function(current_position)
neighbor_positions = [current_position + step_size,
current_position - step_size]
best_neighbor = max(neighbor_positions, key=objective_function)
best_neighbor_value = objective_function(best_neighbor)
if best_neighbor_value > current_value:
current_position = best_neighbor
return current_position, objective_function(current_position)

initial_position = random.uniform(-10, 10) # Start at a random position


step_size = 0.1
max_iterations = 100

best_position, best_value = hill_climbing(initial_position, step_size,


max_iterations)
print(f"Best Position: {best_position}")
print(f"Best Value: {best_value}")
print("Arriyaan Ali Syed")

Output:
Program 12: Use python to solve Quadratic Equation.
Code:

import math

def equationroots(a, b, c):


dis = b * b - 4 * a * c
sqrt_val = math.sqrt(abs(dis))
if dis > 0:
print("real and different roots")
print((-b + sqrt_val) / (2 * a))
print((-b - sqrt_val) / (2 * a))
elif dis == 0:
print("real and same roots")
print(-b / (2 * a))
else:
print("Complex Roots")
print(-b / (2 * a), '+ i', sqrt_val)
print(-b / (2 * a), '- i', sqrt_val)

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

S.NO Name of Program Date of Date of Sign/


. Execution Submission Remarks

You might also like