AI Lab Record
AI Lab Record
P. No.
S.No. Program
(a). Write a python program to print the multiplication table for the given
1.
number?
(b). Write a python program to check whether the given number is prime or
not?
(c). Write a python program to find factorial of the given number?
(a). Write a python program to implement list operations (Nested List,
2.
Length, Concatenation,Membership,Iteration,Indexing and Slicing)?
(b). Write a python program to implement list operations (add, append,
extend & delete)
3. Write a python program to Illustrate Different Set Operations?
1
1(a). Write a python program to print the multiplication table for the given number?
Code:
# Python program to find the multiplication table (from 1 to 10) of a number input by the user
Output:
Display multiplication table of? 5
5x1=5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50
2
1(b). Write a python program to check whether the given number is prime or not?
Code:
# Python program to check if the input number is prime or not
#num = 407
for i in range(2,num):
rem=num%i
if rem == 0:
temp=temp+1
if temp==2:
print(num,"is a prime number")
else:
print(num,"is not a prime number")
Output:
Enter a number: 5
5 is a prime number
3
1(c). Write a python program to find factorial of the given number?
Code:
def recur_factorial(n):
if n == 1:
return n
else:
return n*recur_factorial(n-1)
# uncomment to take input from the user num = int(input("Enter a number: "))
# check is the number is negative
num=int(input("Enter a number: "))
if num < 0:
elif num == 0:
else:
Output:
Enter a number: 5
4
2. (a) Write a python program to implement list operations (Nested List,
Length, Concatenation, Membership, Iteration, Indexing and Slicing)?
Code:
my_list = ['p','r','o','b','e']
# Output: p
print(my_list[0])
print("Length",my_list,":",len(my_list))
# Output: o
print(my_list[2])
# Output: e
print(my_list[4])
# Nested indexing
# Output: 3
print(n_list[0][1])
# Output: 8
print(n_list[1][3])
# Nested List2
# Nested indexing
# Output: a
print(n_list2[0][1])
# Output: 5
print(n_list2[1][3])
concat1=[1,3,5]
concat2=[7,8,9]
print("Concatenation:",concat1,concat2,":",concat1+concat2)
repetion_string="Hello"
print("Repetition:",repetion_string,repetion_string * 4)
Output:
p
Length ['p', 'r', 'o', 'b', 'e']: 5
o
e
3
8
a
5
5
Concatenation: [1, 3, 5] [7, 8, 9] : [1, 3, 5, 7, 8, 9]
Repetition: Hello HelloHelloHelloHello
6
2 (b)Write a python program to implement list operations (add, append, extend
& delete)
Code:
print(myList)
print(len(myList))
print(myList[0])
print(myList[3])
print(myList[1:3])
print(myList[-1])
#print(myList[4])
myList.insert(0,"The")
print(myList)
print(len(myList))
myList.insert(4,"the")
print(myList)
myList.append("continuously")
print(myList)
print(len(myList))
#When use extend the argument should be another list #the elements of that list will
be added #to the current list as individual elements
myList.extend(["for", "sure"])
print(myList)
7
print(len(myList))
myList.append(["The","earth","rotates"])
print(myList)
print(len(myList))
myList.remove("The")
myList.remove(myList[3])
print(myList)
Output
4
Earth
Sun
['revolves', 'around']
Sun
['The', 'Earth', 'revolves', 'around', 'Sun']
5
['The', 'Earth', 'revolves', 'around', 'the', 'Sun']
['The', 'Earth', 'revolves', 'around', 'the', 'Sun', 'continuously'] 7
['The', 'Earth', 'revolves', 'around', 'the', 'Sun', 'continuously', 'for', 'sure'] 9
['The', 'Earth', 'revolves', 'around', 'the', 'Sun', 'continuously', 'for', 'sure', ['The',
'earth', 'rotates']]
10
8
3 Write a python program to Illustrate Different Set Operations?
Code:
Output:
9
4. Write a python program to implement simple Chatbot?
Code:
print("Simple Question and Answering Program")
print("=====================================")
print(" You may ask any one of these questions")
print("Hi")
print("How are you?")
print("Are you working?")
print("What is your name?")
print("what did you do yesterday?")
print("Quit")
while True:
question = input("Enter one question from above list:")
question = question.lower()
if question in ['hi']:
print("Hello")
elif question in ['how are you?','how do you do?']:
print("I am fine")
elif question in ['are you working?','are you doing any
job?']:
print("yes. I'am working in KLU")
elif question in ['what is your name?']:
print("My name is Emilia")
name=input("Enter your name?")
print("Nice name and Nice meeting you",name)
elif question in ['what did you do yesterday?']:
print("I saw Bahubali 5 times")
elif question in ['quit']:
break
10
else:
print("I don't understand what you said")
Output:
11
5.Write a python program to implement Breadth first search Traversal?
Code:
graph = {
'A' : ['B','C'],
'B' : ['D', 'E'],
'C' : ['F'],
'D' : [],
'E' : ['F'],
'F' : []
}
visited = [] # List to keep track of visited nodes.
queue = [] #Initialize a queue
def bfs(visited, graph, node):
visited.append(node)
queue.append(node)
while queue:
s = queue.pop(0)
print (s, end = " ")
for neighbour in graph[s]:
if neighbour not in visited:
visited.append(neighbour)
queue.append(neighbour)
# Driver Code
bfs(visited, graph, 'A')
Output:
A B C D E F
12
6 Write a program to inrplement Depth First Search Traversal.
# Driver Code
print("Following is the Depth-First Search")
dfs(visited, graph, '5')
output:
Following is the Depth-First Search
5
3
2
4
8
7
13
7 Write a prcgram to implernent Water Jug problem.
# This function is used to initialize the
# dictionary elements with a default value.
from collections import defaultdict
print("Steps: ")
14
waterJugSolver(0, 0)
Output:
Steps:
00
40
43
03
30
33
42
02
True
15
8. Write a Program to lmplernent Tic-Tac-Toe game using python.
# Tic-Tac-Toe Program using
# random number in Python
def create_board():
return(np.array([[0, 0, 0],
[0, 0, 0],
[0, 0, 0]]))
def possibilities(board):
l = []
for i in range(len(board)):
for j in range(len(board)):
if board[i][j] == 0:
l.append((i, j))
return(l)
for y in range(len(board)):
if board[x, y] != player:
win = False
continue
if win == True:
return(win)
return(win)
16
# of their marks in a vertical row
for y in range(len(board)):
if board[y][x] != player:
win = False
continue
if win == True:
return(win)
return(win)
def evaluate(board):
winner = 0
winner = player
def play_game():
17
board, winner, counter = create_board(), 0, 1
print(board)
sleep(2)
while winner == 0:
for player in [1, 2]:
board = random_place(board, player)
print("Board after " + str(counter) + " move")
print(board)
sleep(2)
counter += 1
winner = evaluate(board)
if winner != 0:
break
return(winner)
# Driver Code
print("Winner is: " + str(play_game()))
Output:
[[0 0 0]
[0 0 0]
[0 0 0]]
Board after 1 move
[[0 0 0]
[0 0 0]
[0 1 0]]
Board after 2 move
[[0 0 0]
[2 0 0]
[0 1 0]]
Board after 3 move
[[1 0 0]
[2 0 0]
[0 1 0]]
Board after 4 move
[[1 0 0]
[2 2 0]
[0 1 0]]
Board after 5 move
[[1 1 0]
[2 2 0]
[0 1 0]]
Board after 6 move
[[1 1 0]
[2 2 2]
[0 1 0]]
Winner is: 2
18
9. Write a python program to implement k-nearest neighbor algorithm.
KNN
KNN is a simple, supervised machine learning (ML) algorithm that can be used for
classification or regression tasks - and is also frequently used in missing value imputation. It
is based on the idea that the observations closest to a given data point are the most "similar"
observations in a data set, and we can therefore classify unforeseen points based on the
values of the closest existing points. By choosing K, the user can select the number of nearby
observations to use in the algorithm.
Here, we will show you how to implement the KNN algorithm for classification, and show how
different values of K affect the results.
Example
Start by visualizing some data points:
plt.scatter(x, y, c=classes)
plt.show()
Result:
19
#Now we fit the KNN algorithm with K=1:
knn.fit(data, classes)
#Example:
new_x = 8
new_y = 21
new_point = [(new_x, new_y)]
prediction = knn.predict(new_point)
Result:
#Now we do the same thing, but with a higher K value which changes the prediction:
#Example
knn = KNeighborsClassifier(n_neighbors=5)
knn.fit(data, classes)
prediction = knn.predict(new_point)
20
21
10. write a program to implement 8-puzzle problem using python
# Python3 program to print the path from root
# node to destination node for N*N-1 puzzle
# algorithm using Branch and Bound
# The solution assumes that instance of
# puzzle is solvable
# Constructor to initialize a
# Priority Queue
def __init__(self):
self.heap = []
# Node structure
class node:
22
# Stores the matrix
self.mat = mat
count = 0
for i in range(n):
for j in range(n):
if ((mat[i][j]) and
(mat[i][j] != final[i][j])):
count += 1
return count
for i in range(n):
for j in range(n):
23
print("%d " % (mat[i][j]), end = " ")
print()
if root == None:
return
printPath(root.parent)
printMatrix(root.mat)
print()
24
new_tile_pos = [
minimum.empty_tile_pos[0] + row[i],
minimum.empty_tile_pos[1] + col[i], ]
if isSafe(new_tile_pos[0], new_tile_pos[1]):
# Driver Code
# Initial configuration
# Value 0 is used for empty space
initial = [ [ 1, 2, 3 ],
[ 5, 6, 0 ],
[ 7, 8, 4 ] ]
Output:
1 2 3
5 6 0
7 8 4
1 2 3
5 0 6
7 8 4
1 2 3
5 8 6
7 0 4
1 2 3
5 8 6
0 7 4
25
11. Write a program to implement travelling salesman problem using python
def tsp(cost):
# Number of nodes
numNodes = len(cost)
nodes = list(range(1, numNodes))
minCost = float('inf')
return minCost
if __name__ == "__main__":
cost = [
[0, 10, 15, 20],
[10, 0, 35, 25],
[15, 35, 0, 30],
[20, 25, 30, 0]
]
res = tsp(cost)
print(res)
Output:
80
26
12. Write a program to implement regression algorithm using python
x = [5,7,8,7,2,17,2,9,4,11,12,9,6]
y = [99,86,87,88,111,86,103,87,94,78,77,85,86]
plt.scatter(x, y)
plt.show()
x = [5,7,8,7,2,17,2,9,4,11,12,9,6]
y = [99,86,87,88,111,86,103,87,94,78,77,85,86]
def myfunc(x):
return slope * x + intercept
plt.scatter(x, y)
plt.plot(x, mymodel)
plt.show()
27
13. write a python program to implement random forest algorithm
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score, classification_report
import warnings
warnings.filterwarnings('ignore')
# Initialize RandomForestClassifier
rf_classifier = RandomForestClassifier(n_estimators=100, random_state=42)
# Make predictions
y_pred = rf_classifier.predict(X_test)
# Sample prediction
sample = X_test.iloc[0:1] # Keep as DataFrame to match model input format
prediction = rf_classifier.predict(sample)
28
output:
Accuracy: 0.80
Classification Report:
precision recall f1-score support
29
14. Write a program to implement tower of hanoi using python.
# Recursive Python function to solve the tower of hanoi
# Driver code
n = 4
TowerOfHanoi(n,'A','B','C')
# A, C, B are the name of rods
30
15. Write a program to implement monkey banana problem using python
class State:
def __init__(self, monkey, box, banana):
self.monkey = monkey # Position of the monkey
self.box = box # Position of the box
self.banana = banana # Position of the banana
def __str__(self):
return f"Monkey: {self.monkey}, Box: {self.box}, Banana: {self.banana}"
def push_box(state):
if not state.box and not state.monkey:
return State(state.monkey, True, state.banana)
return state
def climb_box(state):
if state.box and not state.monkey:
return State(True, state.box, state.banana)
return state
def grab_banana(state):
if state.monkey and state.banana:
print("Banana grabbed!")
return State(state.monkey, state.box, True)
return state
def monkey_banana_problem():
initial_state = State(False, False, False)
print("Initial State:", initial_state)
state = push_box(initial_state)
print("After pushing the box:", state)
state = climb_box(state)
print("After climbing the box:", state)
state = grab_banana(state)
if __name__ == "__main__":
monkey_banana_problem()
Output:
Initial State: Monkey: False, Box: False, Banana: False
After pushing the box: Monkey: False, Box: True, Banana: False
After climbing the box: Monkey: True, Box: True, Banana: False
31
16. Write a Program to Implement Alpha-Beta pruning using python
# Python3 program to demonstrate
# working of Alpha-Beta Pruning
if maximizingPlayer:
best = MIN
return best
else:
best = MAX
return best
# Driver Code
if __name__ == "__main__":
32
# This code is contributed by Rituraj Jain
Output:
The optimal value is : 5
33
17. Write a program to implement 8 queens problem using python
Output:
[[1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 1, 0, 0, 0], [0,
0, 0, 0, 0, 0, 0, 1], [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 0,
0, 0, 1, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0]]
34