Artificial Intelligence Lab-3
Artificial Intelligence Lab-3
Input:
#a
#Taking Input
number=int(Input("\nEnter a number : "))
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:
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:
if n >= 0:
recursive = fibonacci_r(n)
else:
print("\nPlease enter a non-negative number")
Output:
(f) Program to find the Fibonacci series up to n using non-recursive function
Input:
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)
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******************************")
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")
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.
# 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.
"""
# 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:
Output:
6. program to implement Depth First Search Traversal.
Input:
# Use a set to track visited nodes and avoid processing a node more than once
visited = set()
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
# Perform BFS
while queue:
(x, y), path = queue.popleft()
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 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)
# 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
# KNN parameters
k=3
# 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
# 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
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
# 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
# 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
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
]
Input:
import numpy as np
import matplotlib.pyplot as plt
return m, b
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']
# 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%}")
Input:
'''
s_pole = source pole
i_pole = auxillary pole
d_pole = destination pole
'''
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
#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
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
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': []}
]
}
Input:
N=4
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: