Department of Computer Engineering: Fundamentals of Artificial Intelligence and Machine Learning Lab
Department of Computer Engineering: Fundamentals of Artificial Intelligence and Machine Learning Lab
Department of Computer Engineering: Fundamentals of Artificial Intelligence and Machine Learning Lab
DEPARTMENT OF COMPUTER
ENGINEERING
LAB MANUAL
COURSE
CODE: 5139C
REV
ISION:
2021
SE
ME
ST
ER
-V
INDEX
PAGE
SI.NO EXPERIMENT
NO.
1 DECISION CONTROL
3
STRUCTURES
2 LOOP CONTROL STRUCTURES 4
3 PROGRAMS USING STRING 8
4 PROGRAMS USING LIST 12
5 DICTIONARY MANIPULATIONS 16
6 PROGRAMS USING FUCTIONS 19
7 PROGRAMS USING MODULES 21
8 PROGRAMS USING PACKAGES 22
PROGRAMS USING CLASSES AND
9 25
OBJECTS
PROGRAMS USING REGULAR
10 26
EXPRESSIONS
INSTALLING AND FAMILIARISING
11 27
WEKA
LOADING OF DATA FROM LOCAL
12 FILE SYSTEM, URL AND DB IN 29
WEKA
13 PREPROCESSING PACKAGE 30
14 CLASSIFIERS USING WEKA 33
15 CLASSIFIERS USING PYTHON 36
16 BOT TO PLAY LAST COIN STANDING 38
17 BOT TO PLAY TIC TAC TOE 40
18 OPEN ENDED EXPERIMENT 44
EXPERIMENT 1:
POSITIVE, NEGATIVE OR ZERO
AIM:
To determine if a number is positive, negative, or zero.
PROGRAM:
num = float(input("Enter a number: "))
if num >= 0:
if num == 0:
print("Zero")
else:
print("Positive number")
else:
print("Negative number")
OUTPUT:
Enter a number: 5
Positive number
Enter a number: -8
Negative number
Enter a number: 0
Zero
RESULT:
The program ran successfully and obtained desired output
EXPERIMENT 2:
LEAP YEAR OR NOT
AIM:
To determine if a year is a leap year or not
PROGRAM:
year = 2000
# if not divided by both 400 (century year) and 4 (not century year)
# year is not leap year
else:
print("{0} is not a leap year".format(year))
OUTPUT:
2000 is a leap year
RESULT:
The program ran successfully and obtained desired output
EXPERIMENT 3:
SUM OF ELEMENTS OF A LIST
AIM:
To find Sum of elements of a list.
PROGRAM:
# creating a list
list1 = [11, 5, 17, 18, 23]
OUTPUT:
Sum of all elements in given list: 74
RESULT:
The program ran successfully and obtained desired output.
EXPERIMENT 4:
FACTORIAL OF NUMBER
AIM:
Write a python program to determine factorial of a number using while.
PROGRAM:
print("Enter the Number: ")
num = int(input())
fact = 1
i=1
while i<=num:
fact = fact*i
i = i+1
OUTPUT:
Enter the Number:
5
Factorial = 120
RESULT:
The program ran successfully and obtained desired output
EXPERIMENT 5:
EVEN NUMBERS
AIM:
Write a python program to print even numbers from 1 to 10 using for loop.
PROGRAM:
start, end = 1, 10
# checking condition
if num % 2 == 0:
print(num, end = " ")
OUTPUT:
2 4 6 8 10
RESULT:
The program ran successfully and obtained desired output.
EXPERIMENT 6:
STRINGS
AIM:
Write a python program to read two strings str1 and str2
str2 = "World."
print(str2)
• Write a python program to find the length of string
print(len(str1))
print(len(str2))
output = Str1 * 4
print(output)
8.Write a python program to print letters starting from index 4, ending at index 11
OUTPUT:
• Hello
World.
2. 5
6
3.HelloWorld.
4. HelloHelloHelloHello
5.Hel
6. Yes, String found
7. D
a
t
a
S
c
i
e
n
c
e
8. lo world
RESULT:
The program ran successfully and obtained desired output.
EXPERIMENT 7:
STRING OPERATIONS
AIM:
• Write python program to print the string in reverse order
print(new_string)
• dlroW olleH
• PYTHON IS FUN
• 3
• ['welcome', 'to', 'the', 'jungle']
• Hi World
• 6
Write your word here: iam studying in maidin polytechnic college
iam studying in maidin polytechnic college
i
a
u
i
i
a
i
i
o
e
i
o
e
RESULT
The program ran successfully and obtained desired output.
EXPERIMENT 8:
LIST OPERATIONS
AIM
print(list[2][3])
print(list[3][0])
print(list[4][4])
print(list)
• Adding elements in lists
list1 = ["apple", "banana", "cherry"]
list1.insert(1, "orange")
print(list1)
• Removing elements in list
list1 = ["apple", "banana", "cherry"]
list1.remove("banana")
print(list1)
6.sorting in list
numbers = [1, 3, 4, 2]
numbers.sort()
print(numbers)
7.Merging list
OUTPUT
1.o
a
p
H
n
2. ['Bob', 'Mark', 'Mona', 'Harry', 'Ivaan']
3. ['apple', 'orange', 'banana', 'cherry']
4.['apple', 'cherry']
5. 1
6. None
[1, 2, 3, 4]
• ['apple', 'banana', 'cherry', 'mango', 'pineapple', 'papaya']
RESULT
The program ran successfully and obtained desired output
EXPERIMENT 9:
AIM:
TUPLE OPERATIONS
• Unpacking of tuples
fruits = ("apple", "banana", "cherry")
print(green)
print(yellow)
print(red)
RESULT:
The program ran successfully and obtained desired output
EXPERIMENT 9:
DICTIONARY OPERATIONS
AIM:
# original dictionary
print("initial dictionary-", dict)
# changing the key value from 2 to 4
dict['dita'] = 4
print("Dictionary:", dict1)
print("Length of dictionary:", len(dict1))
#To check presence
my_dict = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
if'key2'in my_dict:
print("key exists in the dictionary.")
else:
print("key does not exist in the dictionary.")
• Merging dictionary elements
dict_1 = {1: 'a', 2: 'b'}
dict_2 = {2: 'c', 4: 'd'}
print(dict_1 | dict_2)
OUTPUT:
1. {1: 'Geeks', 2: 'For', 3: 'Geeks'}
2. initial dictionary- {'hari': 1, 'dita': 2}
dictionary after modification- {'hari': 1, 'dita': 4}
3. Dictionary: {'Name': 'Steve', 'Age': 30, 'Designation': 'Programmer'}
Length of dictionary: 3
key exists in the dictionary.
4. {1: 'a', 2: 'c', 4: 'd'}
RESULT:
The program ran successfully and obtained desired output.
EXPERIMENT NO.11
PROGRAM:
students_data = {"Meena" : [55,88,77,66,44],"Sumedh":[56,78,55,88,70], "Sushil": [44,65,76,33,77]}
print("Original Dictionary : ")
print(students_data)
# searching item in dictionary
name = input("Enter name of student :")
if name in students_data.keys():
print(students_data[name])
else :
print("No student found")
OUTPUT
Original Dictionary :
{'Meena': [55, 88, 77, 66, 44], 'Sumedh': [56, 78, 55, 88, 70], 'Sushil': [44, 65, 76, 33, 77]}
Enter name of student :Meena
[55, 88, 77, 66, 44]
RESULT
The program ran successfully and obtained desired output.
EXPERIMENT NO.12
PYTHON FUNCTIONS
AIM
RESULT
The program ran successfully and obtained desired output
EXPERIMENT NO. 13
PYTHON MODULES
AIM
To create a python program to print the square root, factorial and pi value using math module
PROGRAM
import math as mt
print(mt.sqrt(16))
print(mt.factorial(6))
print("The value of pi is", math.pi)
OUTPUT
4.0
720
The value of pi is 3.141592653589793
RESULT
The program ran successfully and obtained desired output
EXPERIMENT NO.14
AIM
Write a program to familiarize python packages pandas, numpy and matplotlib.
PROGRAM:
**programs using pandas package
import pandas as pd
#load a dataset
data=pd.read_csv("employee.csv")
data
**writing a dataframe
df = pd.DataFrame({'X':[78,85,96,80,86], 'Y':[84,94,89,83,86],'Z':[86,97,96,72,83]});
print(df)
print(a)
#print 2D array
b = np.array([[1,2], [3,4]])
print(b)
**programs using matplotlib
import matplotlib.pyplot as plt
# x axis values
x = [1,2,3]
# corresponding y axis values
y = [2,4,1]
EXPERIMENT15:
PROGRAMS USING CLASSES AND OBJECTS
AIM:
Write a python program to calculate the area of room using class and objects.
PROGRAM:
# create a class
class Room:
length = 0.0
breadth = 0.0
# method to calculate area
def calculate_area(self):
print("Area of Room =", self.length * self.breadth)
OUTPUT:
RESULT:
The program ran successfully and obtained desired output
EXPERIMENT 16:
PROGRAMS USING REGULAR EXPRESSIONS
AIM:
Write a Python program to find the sequences of one upper case letter followed by lower case
letters.
PROGRAM:
import re
def text_match(text):
patterns = '[A-Z]+[a-z]+$'
if re.search(patterns, text):
return 'Found a match!'
else:
return('Not matched!')
print(text_match("AaBbGg"))
print(text_match("Python"))
print(text_match("python"))
print(text_match("PYTHON"))
print(text_match("aA"))
print(text_match("Aa"))
OUTPUT:
RESULT:
The program ran successfully and obtained desired output
EXPERIMENT 17:
DOWNLOAD AND INSTALL WEKA SOFTWARE
AIM:
Install and familiarize the machine learning software WEKA.
PROCEDURE:
RESULT:
Familiarized with weka software.
EXPERIMENT 18:
LOADING DATA IN WEKA SOFTWARE
AIM:
Familiarizing loading of data from local file system, url and DB using WEKA.
PROCEDURE:
RESULT:
Familiarized loading of data in weka software.
EXPERIMENT19:
PREPROCESSING OF DATA
AIM:
Pre-processing a dataset using python packages.
PROGRAM:
import pandas as pd
import numpy as np
df.info()
Checking any null values in dataset
df.isnull().any()
EXPERIMENT 21:
CLASSIFIERS USING WEKA
AIM:
Familiarize with classifiers in weka software.
PROCEDURE
Setting test data
We will use the preprocessed weather data file from the previous lesson. Open the saved file by using
the Open file ... option under the Preprocess tab, click on the Classify.
Before you learn about the available classifiers, let us examine the Test options. You will notice
four testing options as listed below −
• Training set
• Supplied test set
• Cross-validation
• Percentage split
Unless you have your own training set or a client supplied test set, you would use cross-
validation or percentage split options. Under cross-validation, you can set the number of folds in
which entire data would be split and used during each iteration of training. In the percentage
split, you will split the data between training and testing using the set split percentage.
Now, keep the default play option for the output class
Selecting Classifiers
Click on the Choose button and select the following classifier −
weka→classifiers>trees>J48
Click on
the Start button to start the classification process, Let us examine the output shown on the right
hand side of the screen.
Visualize Results
To see the visual representation of the results, right click on the result in the Result list box.
Select Visualize tree to get a visual representation of the traversal tree. Selecting Visualize
classifier errors would plot the results of classification. A cross represents a correctly
classified instance while squares represents incorrectly classified instances. At the lower left
corner of the plot you see a cross that indicates if outlook is sunny then play the game. So this
is a correctly classified instance. To locate instances, you can introduce some jitter in it by
sliding the jitter slide bar.
RESULT:
The program ran successfully and obtained desired output.
EXPERIMENT 21:
AIM:
PROGRAM:
#{SVM Classifier}
from sklearn.svm import SVC
svc = SVC()
svc.fit(X,Y)
prediction = svc.predict(P)
print ("4) Using SVC Prediction is " + str(svc.predict(P)) +"\n")
OUTPUT:
1) Using Decision Tree Prediction is ['male']
RESULT:
The program ran successfully and obtained desired output
EXPERIMENT 22:
BOT TO PLAY LAST COIN
AIM:
Write a Python program to demonstrate a bot to play last coin standing.
PROGRAM:
import random
class LastCoinStanding:
def__init__(self, num_coins=25, max_coins_per_move=4):
self.num_coins = num_coins
self.max_coins_per_move = max_coins_per_move
defplay(self):
print("Welcome to Last Coin Standing!")
whileself.num_coins >0:
print(f"\nCoins left in the pile: {self.num_coins}")
human_move = self.get_human_move()
self.remove_coins(human_move, "Human")
ifself.num_coins <= 0:
print("Human wins!")
break
bot_move = self.get_bot_move()
self.remove_coins(bot_move, "Bot")
ifself.num_coins <= 0:
print("Bot wins!")
defget_human_move(self):
whileTrue:
try:
move = int(input("Enter the number of coins to remove (1-4): "))
if1<= move <= self.max_coins_per_move:
return move
else:
print("Invalid move. Please choose between 1 and 4 coins.")
except ValueError:
print("Invalid input. Please enter a number.")
defget_bot_move(self):
max_bot_move = min(self.num_coins, self.max_coins_per_move)
return random.randint(1, max_bot_move)
if__name__ == "__main__":
game = LastCoinStanding()
game.play()
OUTPUT:
Welcome to Last Coin Standing!
RESULT:
The program ran successfully and obtained desired output
EXPERIMENT 23:
TIC TAC TOE GAME
AIM:
Write a python program to demonstrate a bot to play tic tac toe using python.
PROGRAM:
import random
for i inrange(3):
for j inrange(3):
if board[i][j] == " ":
board[i][j] = "O"
score = minimax(board, 0, False)
board[i][j] = " "
return best_move
if check_win(board, "O"):
return scores["O"]
elif check_win(board, "X"):
return scores["X"]
elif is_board_full(board):
return scores["tie"]
if is_maximizing:
best_score = float("-inf")
for i inrange(3):
for j inrange(3):
if board[i][j] == " ":
board[i][j] = "O"
score = minimax(board, depth + 1, False)
board[i][j] = " "
best_score = max(score, best_score)
return best_score
else:
best_score = float("inf")
for i inrange(3):
for j inrange(3):
if board[i][j] == " ":
board[i][j] = "X"
score = minimax(board, depth + 1, True)
board[i][j] = " "
best_score = min(score, best_score)
return best_score
print("Welcome to Tic-Tac-Toe!")
display_board(board)
whileTrue:
if current_player == "X":
row, col = map(int, input("Enter your move (row and column): ").split())
if board[row][col] != " ":
print("Invalid move. Try again.")
continue
else:
print("Bot is thinking...")
row, col = bot_move(board)
board[row][col] = current_player
display_board(board)
if check_win(board, current_player):
if current_player == "X":
print("You win! Congratulations!")
else:
print("Bot wins! Better luck next time!")
break
elif is_board_full(board):
print("It's a tie!")
break
OUTPUT:
RESULT:
The program ran successfully and obtained desired output
EXPERIMENT 24:
OPEN ENDED EXPERIMENT IN PYTHON
AIM:
Write a python program for number guessing in python.
PROGRAM:
import random
whileTrue:
try:
# Get the player's guess
guess = int(input("Guess the number: "))
attempts += 1
except ValueError:
print("Invalid input. Please enter a valid number.")
OUTPUT:
Welcome to the Number Guessing Game!
I'm thinking of a number between 1 and 100.
Guess the number: 55
Try a lower number.
Guess the number: 22
Try a lower number.
Guess the number: 12
Try a lower number.
Guess the number: 5
Try a lower number.
Guess the number: 1
Try a higher number.
Guess the number: 2
Congratulations! You guessed the number 2 in 6 attempts.
RESULT:
The program ran successfully and obtained desired output.