[go: up one dir, main page]

0% found this document useful (0 votes)
38 views36 pages

Artificial Intelligence Lab-3

The document contains a comprehensive list of Python programs covering various topics such as mathematical operations, data structures, algorithms, and game implementations. Each program includes input, output, and code snippets to demonstrate functionality, including a multiplication table, prime number check, factorial calculation, Fibonacci series, list operations, set operations, a simple chatbot, and graph traversal algorithms. Additionally, it features problem-solving programs like the Water Jug Problem, Tic-Tac-Toe, and other algorithm implementations.
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)
38 views36 pages

Artificial Intelligence Lab-3

The document contains a comprehensive list of Python programs covering various topics such as mathematical operations, data structures, algorithms, and game implementations. Each program includes input, output, and code snippets to demonstrate functionality, including a multiplication table, prime number check, factorial calculation, Fibonacci series, list operations, set operations, a simple chatbot, and graph traversal algorithms. Additionally, it features problem-solving programs like the Water Jug Problem, Tic-Tac-Toe, and other algorithm implementations.
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
You are on page 1/ 36

INDEX

S.NO Program Page No.

a) Program to print multiplication table for given number.


b) Program to check whether the given number is prime or not.
c) Program to find factorial of the given number and similar programs.
1
d) Program to find the factorial of a given number using non-recursive function
e) Program to find the Fibonacci series up to n using recursive function
f) Program to find the Fibonacci series up to n using non-recursive function

program to implement List Operations (Nested list, Length, Concatenation,


2 Membership, Iteration, Indexing and Slicing), List Methods (Add, Append,
Extend & Delete).

3 program to Illustrate Different Set Operations.

4 program to implement Simple Chatbot.

5 program to implement Breadth First Search Traversal.

6 program to implement Depth First Search Traversal.

7 program to implement Water Jug Problem.

8 Program to Implement Tic-Tac-Toe game using Python.

9 program to implement K -Nearest Neighbour algorithm.

10 Program to Implement 8-Puzzle problem using Python.

11 Program to Implement Travelling Salesman Problem using Python.

12 program to implement Regression algorithm.

13 program to implement Random Forest Algorithm.

14 Program to Implement Tower of Hanoi using Python.

15 Program to Implement Monkey Banana Problem using Python.

16 Program to implement Alpha-Beta Pruning using Python.

17 Program to Implement 8-Queens Problem using Python.


1 (a) Program to print multiplication table for a given number

Input:

#a
#Taking Input
number=int(Input("\nEnter a number : "))

print(f"\nMultiplication Table of {number} is : ")

for i in range(1,11):
#Displaying Multiplication Table
print(f"{number} x {i} = {number*i}")

Output:
(b) Program to check whether the given number is prime or not

Input:

#b
num=int(Input("\nEnter a number : "))

if num<2:
# numbers less than 2 are not prime
prime_number=False

else:
prime_number=True
for i in range(2,num):
if num%i==0:
prime_number=False
break
# Exit the loop if any number divides `num`

if prime_number:
print(f"\n{num} is a prime number")

else :
print(f"\n{num} is not a prime number")

Output:
(c) Program to find the factorial of a given number and other similar programs

Input:

#c
number = int(Input("\nEnter a number : "))

def fact_r(n):
if n == 0:
return 1
else:
return n * fact_r(n - 1)

if number>=0:
recursive = fact_r(number)
print(f"\nFactorial of {number} using recursive function is {recursive}")
else:
print("\nPlease enter a positive number")

Output:
(d) Program to find the factorial of a given number using non-recursive function

Input:

#Factorial non recursive


number = int(Input("\nEnter a number : "))

def fact_nonr(n1):
if n1 == 0:
return 1
else:
result = 1
for i in range(1,n1+1):
result *= i
return result

if number>=0:
non_recursive = fact_nonr(number)
print(f"Factorial of {number} using non-recursive function is {non_recursive}")

else:
print("\nPlease enter a positive number")

Output:
(e) Program to find the Fibonacci series up to n using recursive function

Input:

#fibonacci series up to n using recursive function


n = int(Input("\nEnter the maximum number for the Fibonacci series : "))

def fibonacci_r(n, a=0, b=1):


if a > n:
return []
return [a] + fibonacci_r(n, b, a + b)

if n >= 0:
recursive = fibonacci_r(n)

print(f"\nFibonacci series up to {n} using recursive function :")


for element in recursive:
print(element)

else:
print("\nPlease enter a non-negative number")

Output:
(f) Program to find the Fibonacci series up to n using non-recursive function

Input:

#fibonacci series up to n using non recursive function


n = int(Input("\nEnter the maximum number for the Fibonacci series : "))

def fibonacci_nonr(n):
list_nonr = []
a,b=0,1
while a <= n:
list_nonr.append(a)
a,b=b,a+b
return list_nonr

if n >= 0:
nonrecursive = fibonacci_nonr(n)

print(f"\nFibonacci series up to {n} using non-recursive function :")


for element in nonrecursive:
print(element)
else:
print("\nPlease enter a non-negative number")

Output:
2. program to implement List Operations (Nested list, Length, Concatenation, Membership, Iteration,
Indexing and Slicing), List Methods (Add, Append, Extend & Delete).

Input:

inp=['keyboard','mouse']
comp=['control unit','ALU','Internal memory']
output=['monitor','printer']
print(f"\nThe lists are :\n\nInput={inp}\ncomp={comp}\noutput={output}\n\n")

print("*****************************LIST OPERATIONS*****************************")
n_list = [['keyboard', 'mouse'],
['monitor', 'printer'],
['control unit','ALU','Internal memory']]
print('\nNested List creation :\n', n_list)
print('\nlength of "inp" List : ', len(inp))
#concatenation(+) combines two lists
inout=inp+output
print('\nConcatenated List of "inp" and "output" :\n', inout)
print('\nChecking "mouse" membership in "inp" List : ', "mouse" in inp)
print('\nIterating through "comp" elements : ')
for i in comp:
print(i)
print('\nAccessing the last element of the "output" using indexing : ', output[-1])
print('\nSlicing "comp" to get odd-positioned elements :\n', comp[0::2])

print("\n\n******************************LIST METHODS******************************")

#.__add__ method is underlying special method same as '+' concatenation


print('\nAdding "inp" list and "output" list :\n',output.__add__(inp))

# The append() method adds single element to the end of a


# it modifies existing List
output.append("speaker")
print('\nAppending "Speaker" in "output" List :\noutput=',output)

# extend() method adds elements from an iterable(list,tuple,set or dictionary)


# extend() Modifies the exisiting List
comp.extend(inp)
print('\nExtending "comp" list with elements from "inp" :\ncomp=',comp)

#remove method deletes the specified element from the list


inp.remove('keyboard')
print('\nDeleting "keyboard" from inp List :\ninp=',inp)
Output:
3. program to Illustrate Different Set Operations

Input:

set1={1,2,3,4,5,7,8}
set2={6,7,8,9,10,2,4}
print(f"\nThe two sets are:\n \nset1={set1}\nset2={set2}\n")

#performing set operations

# unique elements from set1 and set2.


union = set1.union(set2)
#common elements in set1 and set2
intersection = set1.intersection(set2)
#elements in set2 not in set1.
difference = set2.difference(set1)
#elements unique to either set1 or set2.
s_difference = set1.symmetric_difference(set2)
set1.add(42)
set2.remove(10)

print("\n****************************SET OPERATIONS*****************************")
#printing values
print("\n\nUnion of two sets =",union)
print("\nIntersection of two sets =",intersection)
print("\nDifference of two sets(set2-set1) =",difference)
print("\nSymmetric Difference of two sets (set2 ⊝ set1) =",s_difference)
print("\nAdding '42' to set1:\nset1=",set1)
print("\nRemoving '10' from set2:\nset2=",set2)

Output:
4 program to implement Simple Chatbot.

install the necessary library files:


pip install sklearn (or) pip install scikit-learn
pip install nltk

run the following program:


import nltk
nltk.download("punkt")
nltk.download("wordnet")
nltk.download("omw-1.4")
nltk.download("punkt_tab")
'''
Input:

from sklearn.feature_extraction.text import TfidfVectorizer


from sklearn.metrics.pairwise import cosine_similarity
import nltk

# Sample corpus
corpus = """Hello Adnan how can i help you today?
Python is a versatile programming language.
The latest version of Python as of 2025 is Python 3.13.1.
Yes,i can help you with python programming.
To find the square root of a number in Python, use the math.sqrt() function.
"""

# Preprocess and vectorize


def preprocess(text):
sentences = nltk.sent_tokenize(text)
vectorizer = TfidfVectorizer()
tfidf_matrix = vectorizer.fit_transform(sentences)
return sentences, tfidf_matrix, vectorizer

sentences, tfidf_matrix, vectorizer = preprocess(corpus)

def get_response(user_Input, sentences, tfidf_matrix, vectorizer):


all_sentences = sentences + [user_Input.lower()]
all_tfidf = vectorizer.transform(all_sentences)
similarity_scores = cosine_similarity(all_tfidf[-1], all_tfidf[:-1])
return sentences[similarity_scores.argmax()]

# Chatbot loop
def chatbot():
print("Chatbot: I am a simple chatbot! Type 'exit' to end the conversation.")
while True:
user_Input = Input("You : ")
if user_Input.lower() == 'exit':
print("Chatbot: Goodbye! Have a great day!")
break
else:
response = get_response(user_Input, sentences, tfidf_matrix, vectorizer)
print(f"Chatbot: {response}")

chatbot()
Output:
5. program to implement Breadth First Search Traversal.

Input:

# Define a directed graph using a Python dictionary as an adjacency list


graph = {
'A': ['B', 'C'], # Node 'A' is connected to nodes 'B' and 'C'
'B': ['D', 'E'], # Node 'B' is connected to nodes 'D' and 'E'
'C': ['F'], # Node 'C' is connected to node 'F'
'D': [], # Node 'D' has no outgoing edges
'E': ['F'], # Node 'E' is connected to node 'F'
'F': [] # Node 'F' has no outgoing edges
}

# List to keep track of visited nodes to avoid processing them again


visited = []

# Queue to maintain the nodes to be explored, supporting BFS traversal


queue = []

def bfs(visited, graph, node):


# Add the starting node to visited list and queue
visited.append(node)
queue.append(node)

# Continue traversal while there are nodes in the queue


while queue:
# Remove and return the first node in the queue
s = queue.pop(0)
print(s, end=" -> ") # Print the node in BFS order

# Explore all adjacent nodes (neighbours)


for neighbour in graph[s]:
if neighbour not in visited: # Only visit unvisited nodes
visited.append(neighbour) # Mark the node as visited
queue.append(neighbour) # Add it to the queue for future exploration
print("END")

print("\nBFS Traversal starting from node 'A':\n")


bfs(visited, graph, 'A')

Output:
6. program to implement Depth First Search Traversal.

Input:

# Define a directed graph using a Python dictionary as an adjacency list


graph = {
'A': ['B', 'C'], # Node 'A' connects to nodes 'B' and 'C'
'B': ['D', 'E'], # Node 'B' connects to nodes 'D' and 'E'
'C': ['F'], # Node 'C' connects to node 'F'
'D': [], # Node 'D' has no outgoing edges
'E': ['F'], # Node 'E' connects to node 'F'
'F': [] # Node 'F' has no outgoing edges
}

# Use a set to track visited nodes and avoid processing a node more than once
visited = set()

def dfs(visited, graph, node):


# Proceed only if the node has not been visited
if node not in visited:
# Process the current node (print it)
print(node,end=" -> ")
# Mark the node as visited
visited.add(node)

# Recursively visit all unvisited neighbours


for neighbour in graph[node]:
dfs(visited, graph, neighbour)

print("DFS Traversal starting from node 'A':")


dfs(visited, graph, 'A')
print("END")

Output:
7. program to implement water jug problem.

Input:
'''
a=capacity of big jug
b=capacity of small jug
d=target amount of water for big jug
x=current amount of water in big jug
y=current amount of water in small jug

'''
# The ‘collections.deque’ library provides a double-ended queue that allows fast, efficient appending and popping of
elements from both ends.
from collections import deque

a=5
b=3
d=2

# Function to perform BFS to find the solution


def water_jug_problem(a, b, d):
initial_state = (0, 0) # Both jugs are empty

# Visited states to avoid repeating the same state


visited = set()

queue = deque([(initial_state, [])]) # Queue for BFS

# Perform BFS
while queue:
(x, y), path = queue.popleft()

# check if big jug has the target amount of water


if x == d and y == 0:
return path + [(x, y)]

# Mark the state as visited


if (x, y) in visited:
continue
visited.add((x, y))

# List of possible actions


actions = [
(a, y), # Fill big jug
(x, b), # Fill small jug
(0, y), # Empty big jug
(x, 0), # Empty small jug
(x - min(x, b - y), y + min(x, b - y)), # Pour big jug into small jug
(x + min(y, a - x), y - min(y, a - x)), # Pour small jug into big jug
]
# Add valid new states to the queue
for new_state in actions:
new_x, new_y = new_state
if (new_x, new_y) not in visited:
queue.append((new_state, path + [(x, y)]))

return None # Return None if no solution is found


solution = water_jug_problem(a, b, d)
if solution:
print("\nSteps for the solution:")
for step in solution:
print(step)
else:
print("\nNo solution exists.") # Catch cases where BFS fails unexpectedly

Output:
8. Program to Implement Tic-Tac-Toe game using Python.

Input:

def print_board(board):
print(" ")
for i in range(0, 9, 3):
print(f" {board[i]} | {board[i+1]} | {board[i+2]} ")
if i < 6: print("---|---|---")

def check_win(board, player):


win_patterns = [
[0,1,2], [3,4,5], [6,7,8], # Rows
[0,3,6], [1,4,7], [2,5,8], # Columns
[0,4,8], [2,4,6] # Diagonals
]
return any(board[i] == board[j] == board[k] == player
for i, j, k in win_patterns)

#priority-based heuristic search


def ai_move(board):
# Try to win first
for i in [4,0,2,6,8,1,3,5,7]:
if board[i] == " ":
board[i] = "O"
if check_win(board, "O"):
return
board[i] = " "

# Block human win


for i in [4,0,2,6,8,1,3,5,7]:
if board[i] == " ":
board[i] = "X"
if check_win(board, "X"):
board[i] = "O"
return
board[i] = " "

# Choose best available spot


for i in [4,0,2,6,8,1,3,5,7]:
if board[i] == " ":
board[i] = "O"
return

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

while True:
print_board(board)

if current_player == "X":
# Human turn
while True:
try:
move = int(Input("Your move (1-9): ")) - 1
if 0 <= move <= 8 and board[move] == " ":
board[move] = "X"
break
print("Invalid move! Try again.")
except ValueError:
print("Please enter a number 1-9!")
else:
# AI turn
print("\nAI's turn...")
ai_move(board)

# Check game status


if check_win(board, current_player):
print_board(board)
winner = "Human" if current_player == "X" else "AI" # Modified line
print(f"{winner} wins!") # Changed message
break

if " " not in board:


print_board(board)
print("It's a tie!")
break

# Switch player
current_player = "O" if current_player == "X" else "X"

if __name__ == "__main__":
play_game()

Output:
9. program to implement K -Nearest Neighbour algorithm.

Input:

import numpy as np

# Training data: [Weight, Texture, Fruit]


training_data = np.array([
(120, 3, 'Apple'),
(130, 5, 'Apple'),
(140, 7, 'Apple'),
(160, 9, 'Orange'),
(170, 10, 'Orange')
], dtype=[('weight', int), ('texture', int), ('fruit', 'U10')])

# New data point to classify


new_fruit = np.array([(150, 3)], dtype=[('weight', int), ('texture', int)])

# KNN parameters
k=3

# Calculate Euclidean distances


def calculate_distances(train, new_point):
distances = []
for entry in train:
diff_weight = new_point['weight'] - entry['weight']
diff_texture = new_point['texture'] - entry['texture']
distance = np.sqrt(diff_weight**2 + diff_texture**2)
distances.append((distance, entry['fruit'], entry['weight'], entry['texture']))
return distances

distances = calculate_distances(training_data, new_fruit[0])

# Display Training Data Table


print("\nTraining Data Table:")
print("\nWeight | Texture | Fruit")
print("-------------------------")
for entry in training_data:
print(f"{entry['weight']:6} | {entry['texture']:7} | {entry['fruit']}")

# Display prediction header


print("\n\nPredicting new fruit type with weight 150 and texture 3....\n")

# Display Euclidean distances


print("Euclidean Distances:\n")
for d, fruit, w, t in distances:
print(f"(150,3) to {fruit} ({w}, {t}): {d:.2f}")

# Sort distances and show top neighbors


sorted_distances = sorted(distances, key=lambda x: x[0])
print(f"\n\nTop {k} nearest neighbours (k={k}) to (150,3):")
for d, fruit, _, _ in sorted_distances[:k]:
print(f"{d:.2f} - {fruit}")

# Count votes and predict


counts = {'Apple': 0, 'Orange': 0}
for d, fruit, _, _ in sorted_distances[:k]:
counts[fruit] += 1

# Final prediction
print("\nFinal Prediction:")
print(f"Majority neigbours are '{max(counts, key=counts.get)}'")
print(f"The fruit (150g, Texture 3) is classified as: {max(counts, key=counts.get)}")

Output:
10. Program to Implement 8-Puzzle problem using Python.

Input:

#A PriorityQueue is a thread-safe queue where elements are retrieved in ascending order of priority based on their
natural order or a custom comparison key.
from queue import PriorityQueue

# Define the goal state


goal_state = (1, 2, 3, 4, 5, 6, 7, 8, 0)
# up, down,left, right
MOVES = [(-1, 0), (1, 0), (0, -1), (0, 1)]

# Heuristic function to calculate the Manhattan distance of each tile from the goal state.
def manhattan_distance(state):
distance = 0
for i in range(9):
if state[i] != 0:
goal_pos = goal_state.index(state[i])
distance += abs(i // 3 - goal_pos // 3) + abs(i % 3 - goal_pos % 3)
return distance

def valid_moves(pos):
row, col = pos // 3, pos % 3
for move in MOVES:
new_row, new_col = row + move[0], col + move[1]
if 0 <= new_row < 3 and 0 <= new_col < 3:
yield new_row * 3 + new_col

# A* algorithm to solve the 8-Puzzle problem.


def a_star_search(start_state):

# Initialize the open list with the start state


open_list = PriorityQueue()
open_list.put((0 + manhattan_distance(start_state), 0, start_state, [])) # (f, g, state, path)

# Set of visited states to avoid revisiting


visited = set()
visited.add(start_state)

while not open_list.empty():


_, g, current_state, path = open_list.get()

# Check if we reached the goal


if current_state == goal_state:
return path

# Find the blank space (0)


blank_pos = current_state.index(0)

# Explore valid moves


for new_pos in valid_moves(blank_pos):
new_state = list(current_state)
new_state[blank_pos], new_state[new_pos] = new_state[new_pos], new_state[blank_pos]
new_state = tuple(new_state)

if new_state not in visited:


visited.add(new_state)
new_path = path + [new_state]
f = g + 1 + manhattan_distance(new_state)
open_list.put((f, g + 1, new_state, new_path))

return None # If no solution exists

# Helper function to print the board in a readable format.


def print_board(state):
for i in range(0, 9, 3):
print(state[i:i+3])
print()

start_state = (1, 2, 3, 4, 0, 6, 7, 5, 8) # Example start state


print("\nInitial State:")
print_board(start_state)

solution = a_star_search(start_state)
if solution:
print("\nSolution path:")
for state in solution:
print_board(state)
else:
print("No solution found!")

Output:
11. Program to Implement Travelling Salesman Problem using Python.

Input:

# The itertools library providesfast, memory-efficient tools for working with iterators
import itertools

def calculate_total_distance(distance_matrix, path):


total_distance = 0
# Sum up distances between consecutive cities in the path
for i in range(len(path) - 1):
total_distance += distance_matrix[path[i]][path[i + 1]]
# Add the distance from the last city back to the starting city to complete the cycle
total_distance += distance_matrix[path[-1]][path[0]]
return total_distance

# Function to solve the Travelling Salesman Problem (TSP) using brute force
def travelling_salesman_bruteforce(distance_matrix):
n = len(distance_matrix) # Number of cities
cities = list(range(1, n)) # List of cities excluding the starting city (0)
min_distance = float('inf') # Initialize the minimum distance to infinity
best_path = None # Initialize the best path to None

# Generate all permutations of cities (excluding the starting city)


for perm in itertools.permutations(cities):
path = [0] + list(perm) # Create a path starting from city 0
total_distance = calculate_total_distance(distance_matrix, path)

# Update the best path and minimum distance if a shorter path is found
if total_distance < min_distance:
min_distance = total_distance
best_path = path

return best_path, min_distance

distance_matrix = [
[0, 10, 15, 20], # distances from city 0
[10, 0, 35, 25], # distances from city 1
[15, 35, 0, 30], # distances from city 2
[20, 25, 30, 0] # distances from city 3
]

best_path, min_distance = travelling_salesman_bruteforce(distance_matrix)


# print the results
print("\nThe shortest path is:")
for i in best_path:
print(i,end=" -> ")
print("END")
print(f"\nThe minimum distance is:\n{min_distance}")
Output:
12. program to implement Regression algorithm

Input:

import numpy as np
import matplotlib.pyplot as plt

# Sample dataset (Input Data)


X = np.array([8, 10, 12]) # diameter in inches
y = np.array([10, 13, 16]) # price in dollars

def linear_regression(X, y):


"""Calculate slope (m) and intercept (b) for linear regression"""
mean_x = np.mean(X)
mean_y = np.mean(y)

# Calculate slope (m)


numerator = np.sum((X - mean_x) * (y - mean_y))
denominator = np.sum((X - mean_x) ** 2)
m = numerator / denominator

# Calculate intercept (b)


b = mean_y - m * mean_x

return m, b

def predict(X, m, b):


"""Make predictions using the linear regression model"""
return m * X + b

# Train the model


m, b = linear_regression(X, y)

# Define two diameters to predict


X_test = np.array([15, 20])
predicted_prices = predict(X_test, m, b)

print("\n Linear Regression Equation ")


print("==============================")
print(f"y = {m:.2f}x + {b:.2f}")

# Print Input Data


print("\n Actual Data (Input) ")
print("======================")
print(f"{'Diameter (inches)':<20}{'Actual Price ($)':<20}")
print("-" * 40)
for d, price in zip(X, y):
print(f"{d:<20}{price:<20.2f}")

# Print Predicted Data (Only for 15-inch & 20-inch pizzas)


print("\n Predicted Data ")
print("======================")
print(f"{'Diameter (inches)':<20}{'Predicted Price ($)':<20}")
print("-" * 40)
for d, price in zip(X_test, predicted_prices):
print(f"{d:<20}{price:<20.2f}")
# Plotting
plt.figure(figsize=(10, 5))
plt.scatter(X, y, color='blue', label='Actual Data')
plt.plot(X, predict(X, m, b), color='red', label='Regression Line')
plt.scatter(X_test, predicted_prices, color='green', marker='X', s=100, label='Predictions')
plt.title('Linear Regression for Pizza Price Prediction')
plt.xlabel('Diameter (inches)')
plt.ylabel('Price ($)')
plt.legend()
plt.grid(True)
plt.show()

Output:
13. program to implement Random Forest Algorithm

Input:

import pandas as pd
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score

# Create dataset
data = {
'Hours Studied': [5, 3, 7, 4, 6, 2],
'Attendance (%)': [90, 70, 95, 80, 85, 50],
'Previous Score': [75, 60, 85, 65, 80, 55],
'Pass': [1, 0, 1, 0, 1, 0]
}
df = pd.DataFrame(data)

# Display data
print("\n=== Given Data ===")
print("Hours Studied | Attendance (%) | Previous Score | Pass")
print("-------------------------------------------------------")
for _, row in df.iterrows():
print(f"{row['Hours Studied']:^12} | {row['Attendance (%)']:^14} | {row['Previous Score']:^14} | {row['Pass']:^4}")

# Prepare data
X = df[['Hours Studied', 'Attendance (%)', 'Previous Score']]
y = df['Pass']

# Split data with fixed random_state


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

# Train model
rf = RandomForestClassifier(n_estimators=100, random_state=42)
rf.fit(X_train, y_train)

# Feature importance
print("\n=== Feature Importance ===")
for feature, importance in zip(X.columns, rf.feature_importances_):
print(f"{feature:16} → {importance:.2%}")

# Prediction with proper DataFrame Input


new_data = pd.DataFrame([[4, 88, 70]], columns=X.columns)
prediction = rf.predict(new_data)

new_data = pd.DataFrame([[4, 88, 70]], columns=X.columns)


prediction = rf.predict(new_data)

print("\n=== Example Prediction using Random Forest Algorithm===")


print(f"Input Features:\nHours: {new_data.iloc[0, 0]}, Attendance: {new_data.iloc[0, 1]}%, "
f"Prev Score: {new_data.iloc[0, 2]}")
print(f"Prediction → {'Pass (1)' if prediction[0] == 1 else 'Fail (0)'}")
Output:
14. Program to Implement Tower of Hanoi using Python.

Input:
'''
s_pole = source pole
i_pole = auxillary pole
d_pole = destination pole

disc 1 = smallest disc


disc 2 = medium disc
disc 3 = largest disc

'''
def TowerOfHanoi(n, s_pole, d_pole, i_pole):
# Base case: If there's only one disc, move it directly from source to destination pole
if n == 1:
print("Move disc 1 from pole", s_pole, "to pole", d_pole)
return

# Move n-1 discs from source to intermediate pole


TowerOfHanoi(n - 1, s_pole, i_pole, d_pole)

# Move the nth disc from source to destination pole


print("Move disc", n, "from pole", s_pole, "to pole", d_pole)

# Move the n-1 discs from intermediate pole to destination pole


TowerOfHanoi(n - 1, i_pole, d_pole, s_pole)

#number of disc
n=3
print(f"\nSteps for solving the {n}-disc Tower of Hanoi problem:\n")
# A, C, and B are the source, destination, and intermediate poles respectively
TowerOfHanoi(n, 'A', 'C', 'B')

Output:
15. Program to Implement Monkey Banana Problem using Python.

Input:

import heapq

def heuristic(state):
"""Heuristic function estimating the cost to reach the goal."""
monkey_location, box_location, monkey_on_box, has_banana = state
if has_banana:
return 0 # Goal state
return (monkey_location != box_location) + (box_location != "C") + (not monkey_on_box)

def get_successors(state):
"""Generate all possible successor states."""
monkey_location, box_location, monkey_on_box, has_banana = state
successors = []

if not has_banana:
# Monkey walks to box
if monkey_location != box_location:
successors.append(((box_location, box_location, monkey_on_box, has_banana), "Walk to box"))
# Monkey pushes box to banana
if not monkey_on_box and monkey_location == box_location:
successors.append((("C", "C", monkey_on_box, has_banana), "Push box to banana"))
# Monkey climbs the box
if monkey_location == box_location and not monkey_on_box:
successors.append(((monkey_location, box_location, True, has_banana), "Climb box"))
# Monkey grabs the banana
if monkey_on_box and box_location == "C":
successors.append(((monkey_location, box_location, monkey_on_box, True), "Grab banana"))

return successors

def a_star_search(initial_state):
"""Perform A* search to solve the Monkey and Banana Problem."""
frontier = []
heapq.heappush(frontier, (heuristic(initial_state), 0, initial_state, [])) # (priority, cost, state, path)
explored = set()

while frontier:
_, cost, state, path = heapq.heappop(frontier)

if state in explored:
continue

explored.add(state)
if state[3]: # If has_banana is True
return path

for successor, action in get_successors(state):


if successor not in explored:
new_cost = cost + 1
priority = new_cost + heuristic(successor)
heapq.heappush(frontier, (priority, new_cost, successor, path + [action]))

return None
# Initial state: (monkey_location, box_location, monkey_on_box, has_banana)
initial_state = ("A", "B", False, False)

solution = a_star_search(initial_state)
if solution:
print("Solution found:")
for step in solution:
print(step)
else:
print("No solution found.")

Output:
16. Program to Implement Alpha-Beta Pruning using Python.

Input:

import math

def alpha_beta_pruning(node, depth, alpha, beta, maximizing_player)


if depth == 0 or is_terminal(node):
return evaluate(node)

if maximizing_player:
max_eval = -math.inf
for child in get_children(node):
# Recursively perform alpha-beta pruning for the child node
eval = alpha_beta_pruning(child, depth - 1, alpha, beta, False)
max_eval = max(max_eval, eval)
alpha = max(alpha, eval)
# If alpha is greater than or equal to beta, prune the search tree
if beta <= alpha:
break
return max_eval
else:
min_eval = math.inf
for child in get_children(node):
# Recursively perform alpha-beta pruning for the child node
eval = alpha_beta_pruning(child, depth - 1, alpha, beta, True)
min_eval = min(min_eval, eval)
beta = min(beta, eval)
# If beta is less than or equal to alpha, prune the search tree
if beta <= alpha:
break
return min_eval

def evaluate(node):
return node['value']

def is_terminal(node):
# Check if the node is terminal (no more children)
return node['is_terminal']

def get_children(node):
return node['children']

# Define the root node with value, terminal flag, and children
root = {
'value': 1,
'is_terminal': False,
'children': [
{'value': 3, 'is_terminal': True, 'children': []},
{'value': 4, 'is_terminal': True, 'children': []},
{'value': 6, 'is_terminal': True, 'children': []}
]
}

result = alpha_beta_pruning(root, depth=3, alpha=-math.inf, beta=math.inf, maximizing_player=True)


print("\nOptimal value:", result)
Output:
17. Program to Implement 8-Queens Problem using Python.

Input:

N=4

def is_safe(board, row, col, N):


# Check if there's a queen in the same column
for i in range(row):
if board[i] == col or \
board[i] - i == col - row or \
board[i] + i == col + row:
return False
return True

def solve_n_queens(board, row, N, solutions):


# If all queens are placed, add the solution to the list
if row == N:
# Make a copy of the board
solutions.append(board[:])
return

# Try placing a queen in each column of the current row


for col in range(N):
# Check if placing a queen at (row, col) is safe
if is_safe(board, row, col, N):
board[row] = col
solve_n_queens(board, row + 1, N, solutions)
board[row] = -1

def print_solutions(solutions, N):


for solution in solutions:
# Create an empty board
board = [['.' for _ in range(N)] for _ in range(N)]
for row in range(N):
col = solution[row]
board[row][col] = f'Q{row+1}' # Label queens as Q1, Q2, ..., QN

# Print the board for this solution


for row in board:
print(" ".join(row))
print()

def n_queens(N):
# Initialize an empty board, -1 means no queen in that row
board = [-1] * N
solutions = []
solve_n_queens(board, 0, N, solutions)
print('\nsolutions:\n')
print_solutions(solutions, N)

n_queens(N)
Output:

You might also like