Python Programs
Python Programs
Solve the Tic Tac Toe problem using the Depth First Search technique.
grid = []
line = []
for i in range(3):
for j in range(3):
line.append(" ")
grid.append(line)
line = []
# grid printing
def print_grid():
for i in range(3):
print("|", end="")
for j in range(3):
print(grid[i][j], "|", end="")
print("")
# player turn
def player_turn(turn_player1):
if turn_player1 == True:
turn_player1 = False
print(f"It's {player2}'s turn")
else:
turn_player1 = True
print(f"It's {player1}'s turn")
return turn_player1
# choosing cell
def write_cell(cell):
cell -= 1
i = int(cell / 3)
j = cell % 3
if turn_player1 == True:
grid[i][j] = player1_symbol
else:
grid[i][j] = player2_symbol
return grid
# checking cell
def free_cell(cell):
cell -= 1
i = int(cell / 3)
j = cell % 3
if grid[i][j] == player1_symbol or grid[i][j] == player2_symbol:
print("This cell is not free")
return False
return True
# game opening
print("Welcome to the Tic-Tac-Toe !")
print("")
print_grid()
print("")
player1 = input("Please enter name of player 1 : ")
player1_symbol = input("Please enter the symbol of player 1 : ")
player2 = input("Please enter name of player 2 : ")
player2_symbol = input("Please enter the symbol of player 2 : ")
game = True
full_grid = False
turn_player1 = False
winner = ""
# win check
def win_check(grid, player1_symbol, player2_symbol):
full_grid = True
player1_symbol_count = 0
player2_symbol_count = 0
# checking rows
for i in range(3):
for j in range(3):
if grid[i][j] == player1_symbol:
player1_symbol_count += 1
player2_symbol_count = 0
if player1_symbol_count == 3:
game = False
winner = player1
return game, winner
if grid[i][j] == player2_symbol:
player2_symbol_count += 1
player1_symbol_count = 0
if player2_symbol_count == 3:
game = False
winner = player2
return game, winner
if grid[i][j] == " ":
full_grid = False
player1_symbol_count = 0
player2_symbol_count = 0
# checking columns
player1_symbol_count = 0
player2_symbol_count = 0
for i in range(3):
for j in range(3):
for k in range(3):
if i + k <= 2:
if grid[i + k][j] == player1_symbol:
player1_symbol_count += 1
player2_symbol_count = 0
if player1_symbol_count == 3:
game = False
winner = player1
return game, winner
if grid[i + k][j] == player2_symbol:
player2_symbol_count += 1
player1_symbol_count = 0
if player2_symbol_count == 3:
game = False
winner = player2
return game, winner
if grid[i][j] == " ":
full_grid = False
player1_symbol_count = 0
player2_symbol_count = 0
# checking diagonals
player1_symbol_count = 0
player2_symbol_count = 0
for i in range(3):
for j in range(3):
for k in range(3):
if j + k <= 2 and i + k <= 2:
if grid[i + k][j + k] == player1_symbol:
player1_symbol_count += 1
player2_symbol_count = 0
if player1_symbol_count == 3:
game = False
winner = player1
return game, winner
if grid[i + k][j + k] == player2_symbol:
player2_symbol_count += 1
player1_symbol_count = 0
if player2_symbol_count == 3:
game = False
winner = player2
return game, winner
if grid[i][j] == " ":
full_grid = False
player1_symbol_count = 0
player2_symbol_count = 0
player1_symbol_count = 0
player2_symbol_count = 0
for i in range(3):
for j in range(3):
for k in range(3):
if j - k >= 0 and i + k <= 2:
if grid[i + k][j - k] == player1_symbol:
player1_symbol_count += 1
player2_symbol_count = 0
if player1_symbol_count == 3:
game = False
winner = player1
return game, winner
if grid[i + k][j - k] == player2_symbol:
player2_symbol_count += 1
player1_symbol_count = 0
if player2_symbol_count == 3:
game = False
winner = player2
return game, winner
if grid[i][j] == " ":
full_grid = False
player1_symbol_count = 0
player2_symbol_count = 0
# game
while game == True:
turn_player1 = player_turn(turn_player1)
free_box = False
while free_box == False:
cell = int(input("Please enter a number for your case (1 to 9 from left to
right and from top to bottom) : "))
free_box = free_cell(cell)
grid = write_cell(cell)
print_grid()
game, winner = win_check(grid, player1_symbol, player2_symbol)
# end of game
if winner == player1:
print(f"Winner is {player1} !")
elif winner == player2:
print(f"Winner is {player2} !")
else:
print(f"Grid is full : equality for {player1} and {player2} !")
Program 2:
Show that the 8 - puzzle states are divided into two disjoint sets, such that any
state is reachable from any other state in the same set, while no state is
reachable from any state in the other set.
def count_inversions(state):
"""Count the number of inversions in the given state."""
inversions = 0
flat_state = [tile for tile in state if tile != 0] # Exclude the empty space
(0)
for i in range(len(flat_state)):
for j in range(i + 1, len(flat_state)):
if flat_state[i] > flat_state[j]:
inversions += 1
return inversions
def classify_states(states):
"""Classify states into two sets based on the parity of inversions."""
set_even = []
set_odd = []
Link: https://www.blackbox.ai/chat/0gHrN4a
Program 3:
To Represent and evaluate different scenarios using predicate logic and knowledge
rules.
class Predicate:
def __init__(self, name, *args):
self.name = name
self.args = args
def __repr__(self):
return f"{self.name}({', '.join(map(str, self.args))})"
class KnowledgeBase:
def __init__(self):
self.facts = set()
self.rules = []
return False
# Example predicates
is_mammal = Predicate('is_mammal', 'dog')
is_mammal2 = Predicate('is_mammal', 'cat')
is_bird = Predicate('is_bird', 'sparrow')
# Add facts
kb.add_fact(is_mammal)
kb.add_fact(is_mammal2)
# Define rules
def rule1(kb):
return Predicate('is_mammal', 'dog') in kb.facts
def rule2(kb):
return Predicate('is_bird', 'sparrow') in kb.facts
# Evaluate scenarios
query1 = Predicate('has_fur', 'dog')
query2 = Predicate('can_fly', 'sparrow')
Link: https://www.blackbox.ai/chat/eW4CVNQ
or
class KnowledgeBase:
def __init__(self):
self.facts = {}
self.rules = []
# Define a rule
def can_fly(kb, animal):
if is_bird(kb, animal):
return True
return False
# Add facts
kb.add_fact('mammals', 'dog')
kb.add_fact('mammals', 'cat')
kb.add_fact('birds', 'sparrow')
kb.add_fact('birds', 'eagle')
# Add rules
kb.add_rule({'condition': is_bird, 'conclusion': can_fly})
# Evaluate scenarios
animals_to_check = ['dog', 'sparrow', 'cat', 'eagle']
Program 4: write a python code to apply the find - S and candidate elimination
algorithms to a concept learning task and compare their inductive biases and
outputs
import copy
G = [['?', '?', '?', '?', '?', '?'], ['?', '?', '?', '?', '?', '?'], ['?', '?',
'?', '?', '?', '?'],
['?', '?', '?', '?', '?', '?'], ['?', '?', '?', '?', '?', '?'], ['?', '?',
'?', '?', '?', '?']]
S = ['Null', 'Null', 'Null', 'Null', 'Null', 'Null']
def is_consistent(hypothesis, example):
for i in range(len(hypothesis)):
if hypothesis[i] != '?' and hypothesis[i] != example[i]:
return False
return True
def update_hypotheses_positive(G, S, example):
for i in range(len(G)):
if is_consistent(G[i], example):
continue
else:
for j in range(len(G[i])):
if G[i][j] == '?':
G[i][j] = example[j]
else:
G[i][j] = '?'
for j in range(len(S)):
if S[j] == 'Null':
S[j] = example[j]
elif S[j] != example[j]:
S[j] = '?'
def update_hypotheses_negative(G, S, example):
new_G = copy.deepcopy(G)
for i in range(len(G)):
if not is_consistent(G[i], example):
new_G.remove(G[i])
return new_G
instance1 = ['sunny', 'warm', 'normal', 'strong', 'warm', 'same']
instance2 = ['sunny', 'warm', 'high', 'strong', 'warm', 'same']
instance3 = ['rainy', 'cold', 'high', 'strong', 'warm', 'change']
instance4 = ['sunny', 'warm', 'high', 'strong', 'cool', 'change']
update_hypotheses_positive(G, S, instance1)
print("After instance 1:")
print("G =", G)
print("S =", S)
update_hypotheses_positive(G, S, instance2)
print("\nAfter instance 2:")
print("G =", G)
print("S =", S)
G = update_hypotheses_negative(G, S, instance3)
print("\nAfter instance 3:")
print("G =", G)
print("S =", S)
update_hypotheses_positive(G, S, instance4)
print("\nAfter instance 4:")
print("G =", G)
print("S =", S)
Link: https://www.javatpoint.com/candidate-elimination-algorithm-in-python
Find S Algorithm
import pandas as pd
import numpy as np
print(data, "\n")
return specific_hypothesis
https://www.blackbox.ai/chat/JUXjead
Program 5:
import pandas as pd
df = pd.DataFrame(data)
https://www.blackbox.ai/chat/1GKx7r8
Program 6:
https://www.blackbox.ai/chat/OQJAQqg
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.datasets import make_classification, make_moons, make_circles
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
# Create datasets
datasets = {
"Linear": make_classification(n_samples=100, n_features=2, n_informative=2,
n_redundant=0, random_state=42),
"Moons": make_moons(n_samples=100, noise=0.1, random_state=42),
"Circles": make_circles(n_samples=100, noise=0.1, factor=0.5, random_state=42)
}
train_pred = clf.predict(X_train)
test_pred = clf.predict(X_test)
train_accuracies.append(accuracy_score(y_train, train_pred))
test_accuracies.append(accuracy_score(y_test, test_pred))
# Store results
results = {}
Program 7:
https://www.blackbox.ai/chat/zI39t6T
Program 8:
https://www.blackbox.ai/chat/qWVwR5W
Program 9:
import pandas as pd
housing = pd.read_csv("F:\\python\\housing.csv")
print(housing.head())
https://www.blackbox.ai/chat/Rp09DKf
Program 10:
https://www.geeksforgeeks.org/evaluation-metrics-for-classification-model-in-
python/