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.pdfaquacareser
 
#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.pdfaquapariwar
 
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.pdfanjandavid
 
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.pdfgulshan16175gs
 
Constraint propagation
Constraint propagationConstraint propagation
Constraint propagationPeet Denny
 
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 ).docxbriancrawford30935
 
#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).docxPiersRCoThomsonw
 
New microsoft office word document
New microsoft office word documentNew microsoft office word document
New microsoft office word documentrudrapratap61
 

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

Tree View Decoration Attribute in the Odoo 17
Tree View Decoration Attribute in the Odoo 17Tree View Decoration Attribute in the Odoo 17
Tree View Decoration Attribute in the Odoo 17Celine George
 
Oppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmOppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmStan Meyer
 
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxGrade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxkarenfajardo43
 
Narcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfNarcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfPrerana Jadhav
 
Objectives n learning outcoms - MD 20240404.pptx
Objectives n learning outcoms - MD 20240404.pptxObjectives n learning outcoms - MD 20240404.pptx
Objectives n learning outcoms - MD 20240404.pptxMadhavi Dharankar
 
Mythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITWMythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITWQuiz Club NITW
 
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptxDecoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptxDhatriParmar
 
4.9.24 Social Capital and Social Exclusion.pptx
4.9.24 Social Capital and Social Exclusion.pptx4.9.24 Social Capital and Social Exclusion.pptx
4.9.24 Social Capital and Social Exclusion.pptxmary850239
 
ICS 2208 Lecture Slide Notes for Topic 6
ICS 2208 Lecture Slide Notes for Topic 6ICS 2208 Lecture Slide Notes for Topic 6
ICS 2208 Lecture Slide Notes for Topic 6Vanessa Camilleri
 
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...Nguyen Thanh Tu Collection
 
6 ways Samsung’s Interactive Display powered by Android changes the classroom
6 ways Samsung’s Interactive Display powered by Android changes the classroom6 ways Samsung’s Interactive Display powered by Android changes the classroom
6 ways Samsung’s Interactive Display powered by Android changes the classroomSamsung Business USA
 
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITWQ-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITWQuiz Club NITW
 
Scientific Writing :Research Discourse
Scientific  Writing :Research  DiscourseScientific  Writing :Research  Discourse
Scientific Writing :Research DiscourseAnita GoswamiGiri
 
ARTERIAL BLOOD GAS ANALYSIS........pptx
ARTERIAL BLOOD  GAS ANALYSIS........pptxARTERIAL BLOOD  GAS ANALYSIS........pptx
ARTERIAL BLOOD GAS ANALYSIS........pptxAneriPatwari
 
Sulphonamides, mechanisms and their uses
Sulphonamides, mechanisms and their usesSulphonamides, mechanisms and their uses
Sulphonamides, mechanisms and their usesVijayaLaxmi84
 
Congestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationCongestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationdeepaannamalai16
 
Indexing Structures in Database Management system.pdf
Indexing Structures in Database Management system.pdfIndexing Structures in Database Management system.pdf
Indexing Structures in Database Management system.pdfChristalin Nelson
 
How to Uninstall a Module in Odoo 17 Using Command Line
How to Uninstall a Module in Odoo 17 Using Command LineHow to Uninstall a Module in Odoo 17 Using Command Line
How to Uninstall a Module in Odoo 17 Using Command LineCeline George
 

Recently uploaded (20)

Tree View Decoration Attribute in the Odoo 17
Tree View Decoration Attribute in the Odoo 17Tree View Decoration Attribute in the Odoo 17
Tree View Decoration Attribute in the Odoo 17
 
Oppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmOppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and Film
 
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxGrade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
 
Narcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfNarcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdf
 
Objectives n learning outcoms - MD 20240404.pptx
Objectives n learning outcoms - MD 20240404.pptxObjectives n learning outcoms - MD 20240404.pptx
Objectives n learning outcoms - MD 20240404.pptx
 
Mythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITWMythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITW
 
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptxDecoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
 
4.9.24 Social Capital and Social Exclusion.pptx
4.9.24 Social Capital and Social Exclusion.pptx4.9.24 Social Capital and Social Exclusion.pptx
4.9.24 Social Capital and Social Exclusion.pptx
 
Mattingly "AI & Prompt Design" - Introduction to Machine Learning"
Mattingly "AI & Prompt Design" - Introduction to Machine Learning"Mattingly "AI & Prompt Design" - Introduction to Machine Learning"
Mattingly "AI & Prompt Design" - Introduction to Machine Learning"
 
ICS 2208 Lecture Slide Notes for Topic 6
ICS 2208 Lecture Slide Notes for Topic 6ICS 2208 Lecture Slide Notes for Topic 6
ICS 2208 Lecture Slide Notes for Topic 6
 
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
 
6 ways Samsung’s Interactive Display powered by Android changes the classroom
6 ways Samsung’s Interactive Display powered by Android changes the classroom6 ways Samsung’s Interactive Display powered by Android changes the classroom
6 ways Samsung’s Interactive Display powered by Android changes the classroom
 
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITWQ-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
 
Mattingly "AI & Prompt Design: Large Language Models"
Mattingly "AI & Prompt Design: Large Language Models"Mattingly "AI & Prompt Design: Large Language Models"
Mattingly "AI & Prompt Design: Large Language Models"
 
Scientific Writing :Research Discourse
Scientific  Writing :Research  DiscourseScientific  Writing :Research  Discourse
Scientific Writing :Research Discourse
 
ARTERIAL BLOOD GAS ANALYSIS........pptx
ARTERIAL BLOOD  GAS ANALYSIS........pptxARTERIAL BLOOD  GAS ANALYSIS........pptx
ARTERIAL BLOOD GAS ANALYSIS........pptx
 
Sulphonamides, mechanisms and their uses
Sulphonamides, mechanisms and their usesSulphonamides, mechanisms and their uses
Sulphonamides, mechanisms and their uses
 
Congestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationCongestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentation
 
Indexing Structures in Database Management system.pdf
Indexing Structures in Database Management system.pdfIndexing Structures in Database Management system.pdf
Indexing Structures in Database Management system.pdf
 
How to Uninstall a Module in Odoo 17 Using Command Line
How to Uninstall a Module in Odoo 17 Using Command LineHow to Uninstall a Module in Odoo 17 Using Command Line
How to Uninstall a Module in Odoo 17 Using Command Line
 

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