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

Python Programs

The document contains four separate Python programs addressing different problems. Program 1 implements a Tic Tac Toe game using depth-first search, Program 2 classifies 8-puzzle states based on inversions, Program 3 demonstrates predicate logic and knowledge rules, and Program 4 applies the Find-S and Candidate Elimination algorithms for concept learning. Each program includes functions and logic to achieve its respective task.

Uploaded by

tejalhs1995
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

Python Programs

The document contains four separate Python programs addressing different problems. Program 1 implements a Tic Tac Toe game using depth-first search, Program 2 classifies 8-puzzle states based on inversions, Program 3 demonstrates predicate logic and knowledge rules, and Program 4 applies the Find-S and Candidate Elimination algorithms for concept learning. Each program includes functions and logic to achieve its respective task.

Uploaded by

tejalhs1995
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 12

Pgm 1:

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

# full grid or not


if full_grid == True:
game = False
winner = ""
return game, winner
else:
game = True
winner = ""
return game, winner

# 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 = []

for state in states:


inversions = count_inversions(state)
if inversions % 2 == 0:
set_even.append(state)
else:
set_odd.append(state)

return set_even, set_odd

# Example states (0 represents the empty space)


states = [
[1, 2, 3, 4, 5, 6, 7, 8, 0], # Solved state (0 inversions)
[1, 2, 3, 4, 5, 6, 0, 7, 8], # 1 inversion
[1, 2, 3, 4, 0, 5, 6, 7, 8], # 1 inversion
[1, 2, 3, 0, 4, 5, 6, 7, 8], # 2 inversions
[1, 2, 0, 3, 4, 5, 6, 7, 8], # 2 inversions
[0, 1, 2, 3, 4, 5, 6, 7, 8], # 0 inversions
[1, 0, 2, 3, 4, 5, 6, 7, 8], # 1 inversion
[1, 2, 3, 5, 4, 6, 7, 8, 0], # 3 inversions
]

set_even, set_odd = classify_states(states)

print("States with even inversions:")


for state in set_even:
print(state)

print("\nStates with odd inversions:")


for state in set_odd:
print(state)

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 = []

def add_fact(self, fact):


self.facts.add(fact)

def add_rule(self, rule):


self.rules.append(rule)

def evaluate(self, query):


# Check if the query is a fact
if query in self.facts:
return True
# Evaluate rules
for rule in self.rules:
if rule['condition'](self):
self.facts.add(rule['conclusion'])
if query == rule['conclusion']:
return True

return False

# Example predicates
is_mammal = Predicate('is_mammal', 'dog')
is_mammal2 = Predicate('is_mammal', 'cat')
is_bird = Predicate('is_bird', 'sparrow')

# Create a knowledge base


kb = KnowledgeBase()

# 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

# Add rules with conditions and conclusions


kb.add_rule({'condition': rule1, 'conclusion': Predicate('has_fur', 'dog')})
kb.add_rule({'condition': rule2, 'conclusion': Predicate('can_fly', 'sparrow')})

# Evaluate scenarios
query1 = Predicate('has_fur', 'dog')
query2 = Predicate('can_fly', 'sparrow')

print(f"Does the dog have fur? {kb.evaluate(query1)}") # Should return True


print(f"Can the sparrow fly? {kb.evaluate(query2)}") # Should return True

Link: https://www.blackbox.ai/chat/eW4CVNQ

or

class KnowledgeBase:
def __init__(self):
self.facts = {}
self.rules = []

def add_fact(self, predicate, value):


if predicate not in self.facts:
self.facts[predicate] = set()
self.facts[predicate].add(value)

def add_rule(self, rule):


self.rules.append(rule)

def evaluate(self, predicate, value):


if predicate in self.facts and value in self.facts[predicate]:
return True
for rule in self.rules:
if rule['condition'](self, value):
return rule['conclusion'](self, value)
return False

# Define some predicates


def is_mammal(kb, animal):
return animal in kb.facts.get('mammals', set())

def is_bird(kb, animal):


return animal in kb.facts.get('birds', set())

# Define a rule
def can_fly(kb, animal):
if is_bird(kb, animal):
return True
return False

# Create a knowledge base


kb = KnowledgeBase()

# 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']

for animal in animals_to_check:


if kb.evaluate('mammals', animal):
print(f"{animal} is a mammal.")
elif kb.evaluate('birds', animal):
print(f"{animal} is a bird and can fly: {can_fly(kb, animal)}.")
else:
print(f"{animal} is neither a mammal nor a bird.")

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

Candidate elimination Program.

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

# Read the Excel file


data = pd.read_excel('F:/sample.xlsx')

print(data, "\n")

# Convert the DataFrame to a NumPy array


d = np.array(data)[:, :-1]
print("The attributes are: ", d)

target = np.array(data)[:, -1]


print("The target is: ", target)
def train(c, t):
specific_hypothesis = None # Initialize specific_hypothesis

# Find the first positive example


for i, val in enumerate(t):
if val == "Yes":
specific_hypothesis = c[i].copy()
break

# If no positive example was found, handle the case


if specific_hypothesis is None:
print("No positive examples found.")
return None # or return a default value

# Generalize the hypothesis based on positive examples


for i, val in enumerate(c):
if t[i] == "Yes":
for x in range(len(specific_hypothesis)):
if val[x] != specific_hypothesis[x]:
specific_hypothesis[x] = '?'

return specific_hypothesis

# Print the final hypothesis


final_hypothesis = train(d, target)
if final_hypothesis is not None:
print("The final hypothesis is:", final_hypothesis)

https://www.blackbox.ai/chat/JUXjead

Program 5:

import pandas as pd

# Create a simple dataset


data = {
'Outlook': ['Sunny', 'Sunny', 'Overcast', 'Rain', 'Rain', 'Rain', 'Overcast',
'Sunny', 'Sunny', 'Rain', 'Sunny', 'Overcast', 'Overcast', 'Rain'],
'Temperature': ['Hot', 'Hot', 'Hot', 'Mild', 'Cool', 'Cool', 'Mild', 'Mild',
'Hot', 'Mild', 'Cool', 'Mild', 'Cool', 'Cool'],
'Humidity': ['High', 'High', 'High', 'High', 'Normal', 'Normal', 'Normal',
'High', 'Normal', 'Normal', 'Normal', 'High', 'Normal', 'High'],
'Windy': [False, True, False, False, False, True, True, False, False, False,
True, True, False, True],
'Play': ['No', 'No', 'Yes', 'Yes', 'Yes', 'No', 'Yes', 'No', 'Yes', 'Yes',
'Yes', 'Yes', 'Yes', 'No']
}

df = pd.DataFrame(data)

from sklearn.preprocessing import LabelEncoder

# Initialize label encoders


le = LabelEncoder()

# Encode categorical features


df['Outlook'] = le.fit_transform(df['Outlook'])
df['Temperature'] = le.fit_transform(df['Temperature'])
df['Humidity'] = le.fit_transform(df['Humidity'])
df['Windy'] = le.fit_transform(df['Windy'])
df['Play'] = le.fit_transform(df['Play'])

# Separate features and target variable


X = df.drop('Play', axis=1)
y = df['Play']

from sklearn.tree import DecisionTreeClassifier


from sklearn.model_selection import train_test_split
from sklearn import tree
import matplotlib.pyplot as plt

# Split the dataset into training and testing sets


X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2,
random_state=42)

# Create the decision tree classifier


clf = DecisionTreeClassifier(criterion='entropy', random_state=42)

# Fit the model


clf.fit(X_train, y_train)

# Evaluate the model


accuracy = clf.score(X_test, y_test)
print(f'Accuracy: {accuracy:.2f}')

# Visualize the decision tree


plt.figure(figsize=(12,8))
tree.plot_tree(clf, filled=True, feature_names=X.columns, class_names=['No',
'Yes'])
plt.show()

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)
}

# Function to evaluate decision tree performance


def evaluate_decision_tree(X, y, max_depths):
train_accuracies = []
test_accuracies = []
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3,
random_state=42)

for depth in max_depths:


clf = DecisionTreeClassifier(max_depth=depth, criterion='entropy',
random_state=42)
clf.fit(X_train, y_train)

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

return train_accuracies, test_accuracies

# Define maximum depths to evaluate


max_depths = range(1, 11)

# Store results
results = {}

for name, (X, y) in datasets.items():


train_acc, test_acc = evaluate_decision_tree(X, y, max_depths)
results[name] = (train_acc, test_acc)

# Plotting the results


plt.figure(figsize=(15, 10))

for name, (train_acc, test_acc) in results.items():


plt.plot(max_depths, train_acc, label=f'{name} - Train', marker='o')
plt.plot(max_depths, test_acc, label=f'{name} - Test', marker='x')

plt.title('Decision Tree Performance with Varying Depths')


plt.xlabel('Max Depth')
plt.ylabel('Accuracy')
plt.xticks(max_depths)
plt.ylim(0, 1)
plt.legend()
plt.grid()
plt.show()

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/

You might also like