SlideShare a Scribd company logo
1 of 13
Download to read offline
12. MINMAX ALGORITHM
import math
def minimax(graph, node, depth, maximizing_player):
if depth == 0 or node not in graph:
return max(int(node), 0)
if maximizing_player:
max_value = -math.inf
for neighbor in graph[node]:
value = minimax(graph, neighbor, depth - 1, False)
max_value = max(max_value, value)
return max_value
else:
min_value = math.inf
for neighbor in graph[node]:
value = minimax(graph, neighbor, depth - 1, True)
min_value = min(min_value, value)
return min_value
graph = {
'A': ['B', 'C'],
'B': ['D', 'E', 'F'],
'C': ['G', 'H', 'I'],
'D': ['J', 'K'],
'E': ['L'],
'F': ['M', 'N', 'O'],
'G': ['P'],
'H': ['Q', 'R'],
'I': ['S', 'T', 'U'],
'J': ['4', '3', '5'],
'K': ['2', '1'],
'L': ['4', '2', '3'],
'M': ['5', '4'],
'N': ['7'],
'O': ['3', '2'],
'P': ['1', '4', '0'],
'Q': ['5', '3'],
'R': ['0'],
'S': ['2', '7', '4'],
'T': ['3', '6'],
'U': ['5', '3', '1'],
}
result = minimax(graph, 'A', 4, True)
print("Minimax result:", result)
OUTPUT:
Minimax result: 2
13. ALPHA – BETA PRUNING
class Node:
def __init__(self, value):
self.value = value
self.children = []
def add_child(self, child):
self.children.append(child)
def alpha_beta(node, depth, alpha, beta, maximizing_player):
if depth == 0 or len(node.children) == 0:
return node.value
if maximizing_player:
value = float('-inf')
for child in node.children:
value = max(value, alpha_beta(child, depth - 1, alpha, beta,
False))
alpha = max(alpha, value)
if beta <= alpha:
break
return value
else:
value = float('inf')
for child in node.children:
value = min(value, alpha_beta(child, depth - 1, alpha, beta,
True))
beta = min(beta, value)
if beta <= alpha:
break
return value
root = Node(6)
node1 = Node(3)
node2 = Node(6)
node3 = Node(5)
node4 = Node(5)
node5 = Node(3)
node6 = Node(6)
node7 = Node(7)
node8 = Node(5)
node9 = Node(8)
node10 = Node(5)
node11 = Node(4)
node12 = Node(3)
node13 = Node(6)
node14 = Node(6)
node15 = Node(7)
node16 = Node(5)
node17 = Node(8)
node18 = Node(6)
node19 = Node(5)
node20 = Node(6)
node21 = Node(7)
node22 = Node(4)
node23 = Node(5)
node24 = Node(3)
node25 = Node(6)
node26 = Node(6)
node27 = Node(9)
node28 = Node(7)
node29 = Node(5)
node30 = Node(9)
node31 = Node(8)
node32 = Node(6)
root.add_child(node1)
root.add_child(node2)
root.add_child(node3)
node1.add_child(node4)
node1.add_child(node5)
node2.add_child(node6)
node2.add_child(node7)
node3.add_child(node8)
node3.add_child(node9)
node4.add_child(node10)
node4.add_child(node11)
node5.add_child(node12)
node6.add_child(node13)
node6.add_child(node14)
node7.add_child(node15)
node8.add_child(node16)
node9.add_child(node17)
node9.add_child(node18)
node10.add_child(node19)
node10.add_child(node20)
node11.add_child(node21)
node11.add_child(node22)
node11.add_child(node23)
node12.add_child(node24)
node13.add_child(node25)
node14.add_child(node26)
node14.add_child(node27)
node15.add_child(node28)
node16.add_child(node29)
node17.add_child(node30)
node17.add_child(node31)
node18.add_child(node32)
result = alpha_beta(root, 3, float('-inf'), float('inf'), True)
print("Optimal value:", result)
OUTPUT:
Optimal value: 6
14.ALPHA-BETA PRUNING ON TIC-TAC-TOE GAME
def print_board(board):
for row in board:
print(" | ".join(row))
print("-" * 9)
def initialize_board():
board = [[" " for _ in range(3)] for _ in range(3)]
return board
def make_move(board, row, col, player):
board[row][col] = player
def is_valid_move(board, row, col):
if 0 <= row < 3 and 0 <= col < 3:
if board[row][col] == " ":
return True
return False
def is_board_full(board):
for row in board:
if " " in row:
return False
return True
def has_won(board, player):
for row in board:
if row.count(player) == 3:
return True
for col in range(3):
if board[0][col] == board[1][col] == board[2][col] == player:
return True
if board[0][0] == board[1][1] == board[2][2] == player:
return True
if board[0][2] == board[1][1] == board[2][0] == player:
return True
return False
def evaluate(board):
if has_won(board, "X"):
return 1
elif has_won(board, "O"):
return -1
else:
return 0
def alpha_beta_pruning(board, depth, alpha, beta, is_maximizing):
if has_won(board, "X"):
return 1
elif has_won(board, "O"):
return -1
elif is_board_full(board):
return 0
if is_maximizing:
best_value = float("-inf")
for row in range(3):
for col in range(3):
if is_valid_move(board, row, col):
make_move(board, row, col, "X")
value = alpha_beta_pruning(board, depth + 1, alpha, beta,
False)
undo_move(board, row, col)
best_value = max(best_value, value)
alpha = max(alpha, best_value)
if beta <= alpha:
break
return best_value
else:
best_value = float("inf")
for row in range(3):
for col in range(3):
if is_valid_move(board, row, col):
make_move(board, row, col, "O")
value = alpha_beta_pruning(board, depth + 1, alpha, beta,
True)
undo_move(board, row, col)
best_value = min(best_value, value)
beta = min(beta, best_value)
if beta <= alpha:
break
return best_value
def get_best_move(board):
best_value = float("-inf")
best_move = None
alpha = float("-inf")
beta = float("inf")
for row in range(3):
for col in range(3):
if is_valid_move(board, row, col):
make_move(board, row, col, "X")
value = alpha_beta_pruning(board, 0, alpha, beta, False)
undo_move(board, row, col)
if value > best_value:
best_value = value
best_move = (row, col)
return best_move
def undo_move(board, row, col):
board[row][col] = " "
def play_game():
board = initialize_board()
current_player = "X"
while True:
print_board(board)
if current_player == "X":
print("Player X turn:")
row = int(input("Enter row (0-2): "))
col = int(input("Enter column (0-2): "))
if not is_valid_move(board, row, col):
print("Invalid move. Try again.")
continue
make_move(board, row, col, current_player)
else:
print("Player O turn:")
if is_board_full(board):
print("The board is full. It's a draw!")
break
best_move = get_best_move(board)
if best_move is None:
print("No valid moves left. It's a draw!")
break
make_move(board, best_move[0], best_move[1], current_player)
if has_won(board, current_player):
print_board(board)
print("Player", current_player, "wins!")
break
current_player = "O" if current_player == "X" else "X"
play_game()
OUTPUT:
| |
---------
| |
---------
| |
---------
Player X turn:
Enter row (0-2): 1
Enter column (0-2): 1
| |
---------
| X |
---------
| |
---------
Player O turn:
O | |
---------
| X |
---------
| |
---------
Player X turn:
Enter row (0-2): 1
Enter column (0-2): 0
O | |
---------
X | X |
---------
| |
---------
Player O turn:
O | O |
---------
X | X |
---------
| |
---------
Player X turn:
Enter row (0-2): 1
Enter column (0-2): 2
O | O |
---------
X | X | X
---------
| |
---------
Player X wins!
15.MAP COLORING PROBLEM USING BACK TRACKING
def solve_map_coloring(adjacency_list, colors, region_colors, current_region):
if current_region not in adjacency_list:
return True
for color in colors:
if is_valid(adjacency_list, region_colors, current_region, color):
region_colors[current_region] = color
next_region = get_next_region(adjacency_list, region_colors,
current_region)
if solve_map_coloring(adjacency_list, colors, region_colors,
next_region):
return True
region_colors[current_region] = None
return False
def is_valid(adjacency_list, region_colors, current_region, color):
for neighbor in adjacency_list[current_region]:
if region_colors[neighbor] == color:
return False
return True
def get_next_region(adjacency_list, region_colors, current_region):
for region in adjacency_list:
if region_colors[region] is None:
return region
return None
adjacency_list = {
"WA": ["NT", "SA"],
"NT": ["WA", "SA", "Q"],
"SA": ["WA", "NT", "Q", "NSW", "V"],
"Q": ["NT", "SA", "NSW"],
"NSW": ["Q", "SA", "V"],
"V": ["SA", "NSW"]
}
colors = ["Red", "Green", "Blue"]
region_colors = {region: None for region in adjacency_list}
start_region = next(iter(adjacency_list))
if solve_map_coloring(adjacency_list, colors, region_colors, start_region):
print("Solution:")
for region, color in region_colors.items():
print(f"{region}: {color}")
else:
print("No solution exists for the given map coloring problem.")
OUTPUT:
Solution:
WA: Red
NT: Green
SA: Blue
Q: Red
NSW: Green
V: Red
16. SUDOKO PROBLEM
def find_empty_location(grid):
for row in range(9):
for col in range(9):
if grid[row][col] == 0:
return row, col
return None
def is_valid_number(grid, number, row, col):
return (
not used_in_row(grid, number, row)
and not used_in_col(grid, number, col)
and not used_in_box(grid, number, row - row % 3, col - col % 3)
)
def used_in_row(grid, number, row):
return number in grid[row]
def used_in_col(grid, number, col):
for row in range(9):
if grid[row][col] == number:
return True
return False
def used_in_box(grid, number, start_row, start_col):
for row in range(3):
for col in range(3):
if grid[row + start_row][col + start_col] == number:
return True
return False
def solve_sudoku(grid):
empty_location = find_empty_location(grid)
if not empty_location:
return True
row, col = empty_location
for number in range(1, 10):
if is_valid_number(grid, number, row, col):
grid[row][col] = number
if solve_sudoku(grid):
return True
grid[row][col] = 0
return False
def print_grid(grid):
for i in range(9):
for j in range(9):
print(grid[i][j],end=" ")
print()
grid = [
[5, 3, 0, 0, 7, 0, 0, 0, 0],
[6, 0, 0, 1, 9, 5, 0, 0, 0],
[0, 9, 8, 0, 0, 0, 0, 6, 0],
[8, 0, 0, 0, 6, 0, 0, 0, 3],
[4, 0, 0, 8, 0, 3, 0, 0, 1],
[7, 0, 0, 0, 2, 0, 0, 0, 6],
[0, 6, 0, 0, 0, 0, 2, 8, 0],
[0, 0, 0, 4, 1, 9, 0, 0, 5],
[0, 0, 0, 0, 8, 0, 0, 7, 9]
]
print("INPUT SUDOKO")
print_grid(grid)
print()
if solve_sudoku(grid):
print("Sudoku solution:")
for row in grid:
print(row)
else:
print("No solution exists for the given Sudoku puzzle.")
OUTPUT:
Sudoku solution:
[5, 3, 4, 6, 7, 8, 9, 1, 2]
[6, 7, 2, 1, 9, 5, 3, 4, 8]
[1, 9, 8, 3, 4, 2, 5, 6, 7]
[8, 5, 9, 7, 6, 1, 4, 2, 3]
[4, 2, 6, 8, 5, 3, 7, 9, 1]
[7, 1, 3, 9, 2, 4, 8, 5, 6]
[9, 6, 1, 5, 3, 7, 2, 8, 4]
[2, 8, 7, 4, 1, 9, 6, 3, 5]
[3, 4, 5, 2, 8, 6, 1, 7, 9]
17. CRYPTARITHMETIC PROBLEMS
import itertools
def solve_cryptarithmetic():
digits = list(range(10))
for permutation in itertools.permutations(digits):
S = permutation[0]
E = permutation[1]
N = permutation[2]
D = permutation[3]
M = permutation[4]
O = permutation[5]
R = permutation[6]
Y = permutation[7]
if S == 0 or M == 0:
continue
SEND = S * 1000 + E * 100 + N * 10 + D
MORE = M * 1000 + O * 100 + R * 10 + E
MONEY = M * 10000 + O * 1000 + N * 100 + E * 10 + Y
if SEND + MORE == MONEY:
return SEND, MORE, MONEY
return None
solution = solve_cryptarithmetic()
if solution:
SEND, MORE, MONEY = solution
print("Solution:")
print(" SEND =", SEND)
print(" MORE =", MORE)
print(" MONEY =", MONEY)
else:
print("No solution found.")
OUTPUT:
Solution:
SEND = 9567
MORE = 1085
MONEY = 10652

More Related Content

Similar to p.pdf

#In this project you will write a program play TicTacToe #using tw.pdf
#In this project you will write a program play TicTacToe #using tw.pdf#In this project you will write a program play TicTacToe #using tw.pdf
#In this project you will write a program play TicTacToe #using tw.pdf
aquacareser
 
#In this project you will write a program play TicTacToe #using tw.pdf
#In this project you will write a program play TicTacToe #using tw.pdf#In this project you will write a program play TicTacToe #using tw.pdf
#In this project you will write a program play TicTacToe #using tw.pdf
aquapariwar
 
In Java using Eclipse, Im suppose to write a class that encapsulat.pdf
In Java using Eclipse, Im suppose to write a class that encapsulat.pdfIn Java using Eclipse, Im suppose to write a class that encapsulat.pdf
In Java using Eclipse, Im suppose to write a class that encapsulat.pdf
anjandavid
 
R + Hadoop = Big Data Analytics. How Revolution Analytics' RHadoop Project Al...
R + Hadoop = Big Data Analytics. How Revolution Analytics' RHadoop Project Al...R + Hadoop = Big Data Analytics. How Revolution Analytics' RHadoop Project Al...
R + Hadoop = Big Data Analytics. How Revolution Analytics' RHadoop Project Al...
Revolution Analytics
 
# Imports# Include your imports here, if any are used. import.pdf
 # Imports# Include your imports here, if any are used. import.pdf # Imports# Include your imports here, if any are used. import.pdf
# Imports# Include your imports here, if any are used. import.pdf
gulshan16175gs
 
project 6cards.pyimport randomclass Card( object ).docx
project 6cards.pyimport randomclass Card( object ).docxproject 6cards.pyimport randomclass Card( object ).docx
project 6cards.pyimport randomclass Card( object ).docx
briancrawford30935
 
#include -stdio-h- #include -stdlib-h- #include -stdbool-h- #include - (1).docx
#include -stdio-h- #include -stdlib-h- #include -stdbool-h- #include - (1).docx#include -stdio-h- #include -stdlib-h- #include -stdbool-h- #include - (1).docx
#include -stdio-h- #include -stdlib-h- #include -stdbool-h- #include - (1).docx
PiersRCoThomsonw
 
New microsoft office word document
New microsoft office word documentNew microsoft office word document
New microsoft office word document
rudrapratap61
 

Similar to p.pdf (13)

Python Statistics.pptx
Python Statistics.pptxPython Statistics.pptx
Python Statistics.pptx
 
#In this project you will write a program play TicTacToe #using tw.pdf
#In this project you will write a program play TicTacToe #using tw.pdf#In this project you will write a program play TicTacToe #using tw.pdf
#In this project you will write a program play TicTacToe #using tw.pdf
 
#In this project you will write a program play TicTacToe #using tw.pdf
#In this project you will write a program play TicTacToe #using tw.pdf#In this project you will write a program play TicTacToe #using tw.pdf
#In this project you will write a program play TicTacToe #using tw.pdf
 
In Java using Eclipse, Im suppose to write a class that encapsulat.pdf
In Java using Eclipse, Im suppose to write a class that encapsulat.pdfIn Java using Eclipse, Im suppose to write a class that encapsulat.pdf
In Java using Eclipse, Im suppose to write a class that encapsulat.pdf
 
R + Hadoop = Big Data Analytics. How Revolution Analytics' RHadoop Project Al...
R + Hadoop = Big Data Analytics. How Revolution Analytics' RHadoop Project Al...R + Hadoop = Big Data Analytics. How Revolution Analytics' RHadoop Project Al...
R + Hadoop = Big Data Analytics. How Revolution Analytics' RHadoop Project Al...
 
# Imports# Include your imports here, if any are used. import.pdf
 # Imports# Include your imports here, if any are used. import.pdf # Imports# Include your imports here, if any are used. import.pdf
# Imports# Include your imports here, if any are used. import.pdf
 
Basics
BasicsBasics
Basics
 
Practicle 1.docx
Practicle 1.docxPracticle 1.docx
Practicle 1.docx
 
Constraint propagation
Constraint propagationConstraint propagation
Constraint propagation
 
Oh Composable World!
Oh Composable World!Oh Composable World!
Oh Composable World!
 
project 6cards.pyimport randomclass Card( object ).docx
project 6cards.pyimport randomclass Card( object ).docxproject 6cards.pyimport randomclass Card( object ).docx
project 6cards.pyimport randomclass Card( object ).docx
 
#include -stdio-h- #include -stdlib-h- #include -stdbool-h- #include - (1).docx
#include -stdio-h- #include -stdlib-h- #include -stdbool-h- #include - (1).docx#include -stdio-h- #include -stdlib-h- #include -stdbool-h- #include - (1).docx
#include -stdio-h- #include -stdlib-h- #include -stdbool-h- #include - (1).docx
 
New microsoft office word document
New microsoft office word documentNew microsoft office word document
New microsoft office word document
 

Recently uploaded

Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPSSpellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
AnaAcapella
 
SURVEY I created for uni project research
SURVEY I created for uni project researchSURVEY I created for uni project research
SURVEY I created for uni project research
CaitlinCummins3
 
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
中 央社
 
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
EADTU
 

Recently uploaded (20)

Supporting Newcomer Multilingual Learners
Supporting Newcomer  Multilingual LearnersSupporting Newcomer  Multilingual Learners
Supporting Newcomer Multilingual Learners
 
An overview of the various scriptures in Hinduism
An overview of the various scriptures in HinduismAn overview of the various scriptures in Hinduism
An overview of the various scriptures in Hinduism
 
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPSSpellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
 
SURVEY I created for uni project research
SURVEY I created for uni project researchSURVEY I created for uni project research
SURVEY I created for uni project research
 
Rich Dad Poor Dad ( PDFDrive.com )--.pdf
Rich Dad Poor Dad ( PDFDrive.com )--.pdfRich Dad Poor Dad ( PDFDrive.com )--.pdf
Rich Dad Poor Dad ( PDFDrive.com )--.pdf
 
How to Send Pro Forma Invoice to Your Customers in Odoo 17
How to Send Pro Forma Invoice to Your Customers in Odoo 17How to Send Pro Forma Invoice to Your Customers in Odoo 17
How to Send Pro Forma Invoice to Your Customers in Odoo 17
 
ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...
ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...
ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...
 
The Liver & Gallbladder (Anatomy & Physiology).pptx
The Liver &  Gallbladder (Anatomy & Physiology).pptxThe Liver &  Gallbladder (Anatomy & Physiology).pptx
The Liver & Gallbladder (Anatomy & Physiology).pptx
 
Basic Civil Engineering notes on Transportation Engineering & Modes of Transport
Basic Civil Engineering notes on Transportation Engineering & Modes of TransportBasic Civil Engineering notes on Transportation Engineering & Modes of Transport
Basic Civil Engineering notes on Transportation Engineering & Modes of Transport
 
The Story of Village Palampur Class 9 Free Study Material PDF
The Story of Village Palampur Class 9 Free Study Material PDFThe Story of Village Palampur Class 9 Free Study Material PDF
The Story of Village Palampur Class 9 Free Study Material PDF
 
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
 
How to Manage Website in Odoo 17 Studio App.pptx
How to Manage Website in Odoo 17 Studio App.pptxHow to Manage Website in Odoo 17 Studio App.pptx
How to Manage Website in Odoo 17 Studio App.pptx
 
OS-operating systems- ch05 (CPU Scheduling) ...
OS-operating systems- ch05 (CPU Scheduling) ...OS-operating systems- ch05 (CPU Scheduling) ...
OS-operating systems- ch05 (CPU Scheduling) ...
 
Including Mental Health Support in Project Delivery, 14 May.pdf
Including Mental Health Support in Project Delivery, 14 May.pdfIncluding Mental Health Support in Project Delivery, 14 May.pdf
Including Mental Health Support in Project Delivery, 14 May.pdf
 
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
 
Spring gala 2024 photo slideshow - Celebrating School-Community Partnerships
Spring gala 2024 photo slideshow - Celebrating School-Community PartnershipsSpring gala 2024 photo slideshow - Celebrating School-Community Partnerships
Spring gala 2024 photo slideshow - Celebrating School-Community Partnerships
 
diagnosting testing bsc 2nd sem.pptx....
diagnosting testing bsc 2nd sem.pptx....diagnosting testing bsc 2nd sem.pptx....
diagnosting testing bsc 2nd sem.pptx....
 
8 Tips for Effective Working Capital Management
8 Tips for Effective Working Capital Management8 Tips for Effective Working Capital Management
8 Tips for Effective Working Capital Management
 
male presentation...pdf.................
male presentation...pdf.................male presentation...pdf.................
male presentation...pdf.................
 
Observing-Correct-Grammar-in-Making-Definitions.pptx
Observing-Correct-Grammar-in-Making-Definitions.pptxObserving-Correct-Grammar-in-Making-Definitions.pptx
Observing-Correct-Grammar-in-Making-Definitions.pptx
 

p.pdf

  • 1. 12. MINMAX ALGORITHM import math def minimax(graph, node, depth, maximizing_player): if depth == 0 or node not in graph: return max(int(node), 0) if maximizing_player: max_value = -math.inf for neighbor in graph[node]: value = minimax(graph, neighbor, depth - 1, False) max_value = max(max_value, value) return max_value else: min_value = math.inf for neighbor in graph[node]: value = minimax(graph, neighbor, depth - 1, True) min_value = min(min_value, value) return min_value graph = { 'A': ['B', 'C'], 'B': ['D', 'E', 'F'], 'C': ['G', 'H', 'I'], 'D': ['J', 'K'], 'E': ['L'], 'F': ['M', 'N', 'O'], 'G': ['P'], 'H': ['Q', 'R'], 'I': ['S', 'T', 'U'], 'J': ['4', '3', '5'], 'K': ['2', '1'], 'L': ['4', '2', '3'], 'M': ['5', '4'], 'N': ['7'], 'O': ['3', '2'], 'P': ['1', '4', '0'], 'Q': ['5', '3'], 'R': ['0'], 'S': ['2', '7', '4'], 'T': ['3', '6'], 'U': ['5', '3', '1'], } result = minimax(graph, 'A', 4, True) print("Minimax result:", result) OUTPUT: Minimax result: 2
  • 2. 13. ALPHA – BETA PRUNING class Node: def __init__(self, value): self.value = value self.children = [] def add_child(self, child): self.children.append(child) def alpha_beta(node, depth, alpha, beta, maximizing_player): if depth == 0 or len(node.children) == 0: return node.value if maximizing_player: value = float('-inf') for child in node.children: value = max(value, alpha_beta(child, depth - 1, alpha, beta, False)) alpha = max(alpha, value) if beta <= alpha: break return value else: value = float('inf') for child in node.children: value = min(value, alpha_beta(child, depth - 1, alpha, beta, True)) beta = min(beta, value) if beta <= alpha: break return value root = Node(6) node1 = Node(3) node2 = Node(6) node3 = Node(5) node4 = Node(5) node5 = Node(3) node6 = Node(6) node7 = Node(7) node8 = Node(5) node9 = Node(8) node10 = Node(5) node11 = Node(4) node12 = Node(3) node13 = Node(6) node14 = Node(6) node15 = Node(7) node16 = Node(5) node17 = Node(8) node18 = Node(6)
  • 3. node19 = Node(5) node20 = Node(6) node21 = Node(7) node22 = Node(4) node23 = Node(5) node24 = Node(3) node25 = Node(6) node26 = Node(6) node27 = Node(9) node28 = Node(7) node29 = Node(5) node30 = Node(9) node31 = Node(8) node32 = Node(6) root.add_child(node1) root.add_child(node2) root.add_child(node3) node1.add_child(node4) node1.add_child(node5) node2.add_child(node6) node2.add_child(node7) node3.add_child(node8) node3.add_child(node9) node4.add_child(node10) node4.add_child(node11) node5.add_child(node12) node6.add_child(node13) node6.add_child(node14) node7.add_child(node15) node8.add_child(node16) node9.add_child(node17) node9.add_child(node18) node10.add_child(node19) node10.add_child(node20) node11.add_child(node21) node11.add_child(node22) node11.add_child(node23) node12.add_child(node24) node13.add_child(node25) node14.add_child(node26) node14.add_child(node27) node15.add_child(node28) node16.add_child(node29) node17.add_child(node30) node17.add_child(node31) node18.add_child(node32)
  • 4. result = alpha_beta(root, 3, float('-inf'), float('inf'), True) print("Optimal value:", result) OUTPUT: Optimal value: 6
  • 5. 14.ALPHA-BETA PRUNING ON TIC-TAC-TOE GAME def print_board(board): for row in board: print(" | ".join(row)) print("-" * 9) def initialize_board(): board = [[" " for _ in range(3)] for _ in range(3)] return board def make_move(board, row, col, player): board[row][col] = player def is_valid_move(board, row, col): if 0 <= row < 3 and 0 <= col < 3: if board[row][col] == " ": return True return False def is_board_full(board): for row in board: if " " in row: return False return True def has_won(board, player): for row in board: if row.count(player) == 3: return True for col in range(3): if board[0][col] == board[1][col] == board[2][col] == player: return True if board[0][0] == board[1][1] == board[2][2] == player: return True if board[0][2] == board[1][1] == board[2][0] == player: return True return False def evaluate(board): if has_won(board, "X"): return 1 elif has_won(board, "O"): return -1 else: return 0 def alpha_beta_pruning(board, depth, alpha, beta, is_maximizing): if has_won(board, "X"): return 1 elif has_won(board, "O"): return -1 elif is_board_full(board): return 0 if is_maximizing:
  • 6. best_value = float("-inf") for row in range(3): for col in range(3): if is_valid_move(board, row, col): make_move(board, row, col, "X") value = alpha_beta_pruning(board, depth + 1, alpha, beta, False) undo_move(board, row, col) best_value = max(best_value, value) alpha = max(alpha, best_value) if beta <= alpha: break return best_value else: best_value = float("inf") for row in range(3): for col in range(3): if is_valid_move(board, row, col): make_move(board, row, col, "O") value = alpha_beta_pruning(board, depth + 1, alpha, beta, True) undo_move(board, row, col) best_value = min(best_value, value) beta = min(beta, best_value) if beta <= alpha: break return best_value def get_best_move(board): best_value = float("-inf") best_move = None alpha = float("-inf") beta = float("inf") for row in range(3): for col in range(3): if is_valid_move(board, row, col): make_move(board, row, col, "X") value = alpha_beta_pruning(board, 0, alpha, beta, False) undo_move(board, row, col) if value > best_value: best_value = value best_move = (row, col) return best_move def undo_move(board, row, col): board[row][col] = " " def play_game(): board = initialize_board() current_player = "X" while True:
  • 7. print_board(board) if current_player == "X": print("Player X turn:") row = int(input("Enter row (0-2): ")) col = int(input("Enter column (0-2): ")) if not is_valid_move(board, row, col): print("Invalid move. Try again.") continue make_move(board, row, col, current_player) else: print("Player O turn:") if is_board_full(board): print("The board is full. It's a draw!") break best_move = get_best_move(board) if best_move is None: print("No valid moves left. It's a draw!") break make_move(board, best_move[0], best_move[1], current_player) if has_won(board, current_player): print_board(board) print("Player", current_player, "wins!") break current_player = "O" if current_player == "X" else "X" play_game() OUTPUT: | | --------- | | --------- | | --------- Player X turn: Enter row (0-2): 1 Enter column (0-2): 1 | | --------- | X | --------- | | --------- Player O turn: O | | --------- | X | --------- | |
  • 8. --------- Player X turn: Enter row (0-2): 1 Enter column (0-2): 0 O | | --------- X | X | --------- | | --------- Player O turn: O | O | --------- X | X | --------- | | --------- Player X turn: Enter row (0-2): 1 Enter column (0-2): 2 O | O | --------- X | X | X --------- | | --------- Player X wins!
  • 9. 15.MAP COLORING PROBLEM USING BACK TRACKING def solve_map_coloring(adjacency_list, colors, region_colors, current_region): if current_region not in adjacency_list: return True for color in colors: if is_valid(adjacency_list, region_colors, current_region, color): region_colors[current_region] = color next_region = get_next_region(adjacency_list, region_colors, current_region) if solve_map_coloring(adjacency_list, colors, region_colors, next_region): return True region_colors[current_region] = None return False def is_valid(adjacency_list, region_colors, current_region, color): for neighbor in adjacency_list[current_region]: if region_colors[neighbor] == color: return False return True def get_next_region(adjacency_list, region_colors, current_region): for region in adjacency_list: if region_colors[region] is None: return region return None adjacency_list = { "WA": ["NT", "SA"], "NT": ["WA", "SA", "Q"], "SA": ["WA", "NT", "Q", "NSW", "V"], "Q": ["NT", "SA", "NSW"], "NSW": ["Q", "SA", "V"], "V": ["SA", "NSW"] } colors = ["Red", "Green", "Blue"] region_colors = {region: None for region in adjacency_list} start_region = next(iter(adjacency_list)) if solve_map_coloring(adjacency_list, colors, region_colors, start_region): print("Solution:") for region, color in region_colors.items(): print(f"{region}: {color}") else: print("No solution exists for the given map coloring problem.")
  • 10. OUTPUT: Solution: WA: Red NT: Green SA: Blue Q: Red NSW: Green V: Red
  • 11. 16. SUDOKO PROBLEM def find_empty_location(grid): for row in range(9): for col in range(9): if grid[row][col] == 0: return row, col return None def is_valid_number(grid, number, row, col): return ( not used_in_row(grid, number, row) and not used_in_col(grid, number, col) and not used_in_box(grid, number, row - row % 3, col - col % 3) ) def used_in_row(grid, number, row): return number in grid[row] def used_in_col(grid, number, col): for row in range(9): if grid[row][col] == number: return True return False def used_in_box(grid, number, start_row, start_col): for row in range(3): for col in range(3): if grid[row + start_row][col + start_col] == number: return True return False def solve_sudoku(grid): empty_location = find_empty_location(grid) if not empty_location: return True row, col = empty_location for number in range(1, 10): if is_valid_number(grid, number, row, col): grid[row][col] = number if solve_sudoku(grid): return True grid[row][col] = 0 return False def print_grid(grid): for i in range(9): for j in range(9): print(grid[i][j],end=" ") print() grid = [
  • 12. [5, 3, 0, 0, 7, 0, 0, 0, 0], [6, 0, 0, 1, 9, 5, 0, 0, 0], [0, 9, 8, 0, 0, 0, 0, 6, 0], [8, 0, 0, 0, 6, 0, 0, 0, 3], [4, 0, 0, 8, 0, 3, 0, 0, 1], [7, 0, 0, 0, 2, 0, 0, 0, 6], [0, 6, 0, 0, 0, 0, 2, 8, 0], [0, 0, 0, 4, 1, 9, 0, 0, 5], [0, 0, 0, 0, 8, 0, 0, 7, 9] ] print("INPUT SUDOKO") print_grid(grid) print() if solve_sudoku(grid): print("Sudoku solution:") for row in grid: print(row) else: print("No solution exists for the given Sudoku puzzle.") OUTPUT: Sudoku solution: [5, 3, 4, 6, 7, 8, 9, 1, 2] [6, 7, 2, 1, 9, 5, 3, 4, 8] [1, 9, 8, 3, 4, 2, 5, 6, 7] [8, 5, 9, 7, 6, 1, 4, 2, 3] [4, 2, 6, 8, 5, 3, 7, 9, 1] [7, 1, 3, 9, 2, 4, 8, 5, 6] [9, 6, 1, 5, 3, 7, 2, 8, 4] [2, 8, 7, 4, 1, 9, 6, 3, 5] [3, 4, 5, 2, 8, 6, 1, 7, 9]
  • 13. 17. CRYPTARITHMETIC PROBLEMS import itertools def solve_cryptarithmetic(): digits = list(range(10)) for permutation in itertools.permutations(digits): S = permutation[0] E = permutation[1] N = permutation[2] D = permutation[3] M = permutation[4] O = permutation[5] R = permutation[6] Y = permutation[7] if S == 0 or M == 0: continue SEND = S * 1000 + E * 100 + N * 10 + D MORE = M * 1000 + O * 100 + R * 10 + E MONEY = M * 10000 + O * 1000 + N * 100 + E * 10 + Y if SEND + MORE == MONEY: return SEND, MORE, MONEY return None solution = solve_cryptarithmetic() if solution: SEND, MORE, MONEY = solution print("Solution:") print(" SEND =", SEND) print(" MORE =", MORE) print(" MONEY =", MONEY) else: print("No solution found.") OUTPUT: Solution: SEND = 9567 MORE = 1085 MONEY = 10652