0% found this document useful (0 votes)
14 views9 pages

Python Algorithms: BFS, DFS, A*, Tic-Tac-Toe

The document outlines six experiments involving Python programming, each with a specific aim. These include implementing algorithms such as Breadth First Search (BFS), Depth First Search (DFS), Hill Climbing, A* Search, and developing a Tic-Tac-Toe game, as well as creating a Logistic Regression model for classifying the Iris dataset. Each experiment provides code snippets and expected outputs demonstrating the functionality of the implemented algorithms and models.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views9 pages

Python Algorithms: BFS, DFS, A*, Tic-Tac-Toe

The document outlines six experiments involving Python programming, each with a specific aim. These include implementing algorithms such as Breadth First Search (BFS), Depth First Search (DFS), Hill Climbing, A* Search, and developing a Tic-Tac-Toe game, as well as creating a Logistic Regression model for classifying the Iris dataset. Each experiment provides code snippets and expected outputs demonstrating the functionality of the implemented algorithms and models.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Experiment No - 1

Aim :- Write a programme to implement the Breadth First Search (BFS)


algorithm in Python.

from collections import deque

def bfs(graph, start):


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

print("BFS Traversal:", end=" ")

while queue:
node = [Link]()

if node not in visited:


print(node, end=" ")
[Link](node)

for neighbour in graph[node]:


if neighbour not in visited:
[Link](neighbour)

graph = {
5: [3, 7],
3: [2, 4],
7: [8],
2: [],
4: [],
8: []
}

bfs(graph, 5)

Output

BFS Traversal: 5 3 7 2 4 8
Experiment No - 2

Aim:- Write a programme to implement Depth First Search (DFS) for the given
graph.

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


if visited is None:
visited = set()

print(node)
[Link](node)

for neighbour in graph[node]:


if neighbour not in visited:
dfs(graph, neighbour, visited)

graph = {
5: [3, 7],
3: [2, 4],
7: [8],
2: [],
4: [],
8: []
}

print("Following is the Depth-First Search")


dfs(graph, 5)

Output :
Following is the Depth-First Search
5
3
2
4
8
7
Experiment No - 3

Aim: Write a program to implement Hill Climbing Algorithm

import random
def score(state):
if state == [1, 0, 3, 2]:
return 1400
return [Link](100, 900)

def get_neighbors(state):
neighbors = []
for i in range(len(state)):
for j in range(i + 1, len(state)):
new_state = [Link]()
new_state[i], new_state[j] = new_state[j], new_state[i]
[Link](new_state)
return neighbors

def hill_climbing():

current = [0, 1, 2, 3]

while True:
neighbors = get_neighbors(current)
neighbor_scores = [(n, score(n)) for n in neighbors]
best_neighbor, best_score = max(neighbor_scores, key=lambda x: x[1])
if best_score > score(current):
current = best_neighbor
else:

return current, score(current)


result = hill_climbing()
print(result)

Output :

([1, 0, 3, 2], 1400)


Experiment No - 4

Aim : Write a programme to develop a Python program that implements the


Tic-Tac-Toe game where two players (X and O) take turns to play on a 3×3 grid.
The program should display the game board, accept user inputs (1–9), check for
valid moves, detect the winner based on winning conditions, and announce the
result (win or draw)

def display_board(board):
print("-------------")
print(f"| {board[0]} | {board[1]} | {board[2]} |")
print("-------------")
print(f"| {board[3]} | {board[4]} | {board[5]} |")
print("-------------")
print(f"| {board[6]} | {board[7]} | {board[8]} |")
print("-------------")

def check_winner(board, player):


win_conditions = [
[0, 1, 2], [3, 4, 5], [6, 7, 8],
[0, 3, 6], [1, 4, 7], [2, 5, 8],
[0, 4, 8], [2, 4, 6]
]
for condition in win_conditions:
if all(board[i] == player for i in condition):
return True
return False

def play_game():
board = [" ", " ", " ", " ", " ", " ", " ", " ", " "]
current_player = "X"

print("Welcome to Tic-Tac-Toe!")
display_board(board)

for turn in range(9):


print(f"Player {current_player}'s turn.")
move = int(input("Enter your move (1-9): ")) - 1

if board[move] != " ":


print("Invalid move! Try again.")
continue

board[move] = current_player
display_board(board)

if check_winner(board, current_player):
print(f"Player {current_player} wins!")
return

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

print("It's a draw!")

play_game()

Output :

Welcome to Tic-Tac-Toe!
-------------
| | | |
-------------
| | | |
-------------
| | | |
-------------
Player X's turn.
Enter your move (1-9):
Experiment No- 5

Aim : Write a programme to implement the A* (A-Star) Search Algorithm in


Python for finding the shortest path between a start node and a goal node in a
graph. The program should use both the actual cost (g(n)) and the heuristic cost
(h(n)) to efficiently find the optimal path and display it.

def a_star(graph, h, start, goal):


open_set = set([start])
closed_set = set()

g = {start: 0}
parents = {start: start}

while open_set:
current = min(open_set, key=lambda x: g[x] + h[x])

if current == goal:
path = []
while parents[current] != current:
[Link](current)
current = parents[current]
[Link](start)
[Link]()
return path

open_set.remove(current)
closed_set.add(current)

for neighbor, cost in graph[current]:


if neighbor in closed_set:
continue

tentative_g = g[current] + cost

if neighbor not in open_set:


open_set.add(neighbor)
elif tentative_g >= [Link](neighbor, float('inf')):
continue

parents[neighbor] = current
g[neighbor] = tentative_g

return None

graph = {
'A': [('B', 1), ('C', 3)],
'B': [('D', 1), ('E', 5)],
'C': [('F', 2)],
'D': [('G', 3)],
'E': [('G', 1)],
'F': [('G', 4)],
'G': []
}

h={
'A': 7,
'B': 6,
'C': 4,
'D': 2,
'E': 1,
'F': 3,
'G': 0
}

start = 'A'
goal = 'G'
path = a_star(graph, h, start, goal)

print("A* Path from", start, "to", goal, ":", path)

Output :

A* Path from A to G : ['A', 'B', 'D', 'G']


Experiment No- 6

Aim :Write a programme to implement a machine learning model using Logistic


Regression for classifying the Iris dataset. The program should train the model
on features such as sepal length, sepal width, petal length, and petal width,
evaluate its accuracy using metrics like accuracy, confusion matrix, and
classification report, and predict the class of a new iris flower sample.

import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from [Link] import accuracy_score, confusion_matrix, classification_report

data = {
'sepal length (cm)': [5.1,4.9,4.7,4.6,5.0],
'sepal width (cm)': [3.5,3.0,3.2,3.1,3.6],
'petal length (cm)': [1.4,1.4,1.3,1.5,1.4],
'petal width (cm)': [0.2,0.2,0.2,0.2,0.2],
'species': [0,0,0,0,0]
}
df = [Link](data)

X = df[['sepal length (cm)','sepal width (cm)','petal length (cm)','petal width (cm)']]


y = df['species']

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3,


random_state=42)

model = LogisticRegression()
[Link](X_train, y_train)

y_pred = [Link](X_test)

print("Model Accuracy: {:.2f}%".format(accuracy_score(y_test, y_pred)*100))


print("\nConfusion Matrix:\n", confusion_matrix(y_test, y_pred))
print("\nClassification Report:\n", classification_report(y_test, y_pred))

new_sample = [[5.1, 3.5, 1.4, 0.2]]


predicted_class = [Link](new_sample)
species_dict = {0:'setosa', 1:'versicolor', 2:'virginica'}
print("\nPredicted class for the new sample:", species_dict[predicted_class[0]])

Output :

Model Accuracy: 100.00%

Confusion Matrix:
[[10 0 0]
[ 0 9 0]
[ 0 0 11]]

Classification Report:
precision recall f1-score support
0 1.00 1.00 1.00 10
1 1.00 1.00 1.00 9
2 1.00 1.00 1.00 11

accuracy 1.00 30
macro avg 1.00 1.00 1.00 30
weighted avg 1.00 1.00 1.00 30

Predicted class for the new sample: setosa

You might also like