0% found this document useful (0 votes)
19 views67 pages

Jochu ML

Uploaded by

sahadrmdt
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)
19 views67 pages

Jochu ML

Uploaded by

sahadrmdt
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/ 67

Page |1

GOVT. WOMEN’S
POLYTECHNIC COLLEGE
KALAMASSERY

LABORATORY RECORD

NAME : JYOLSNA E.B

BRANCH :COMPUTER ENGINEERING

REG NO :2201132207

YEAR :2024
Page |2

GOVT. WOMEN’S
POLYTECHNIC COLLEGE
KALAMASSERY

LABORATORY RECORD

NAME : JYOLSNA E.B

BRANCH :COMPUTER ENGINEERING

REG NO :2201132207

YEAR :2024

CERTIFICATE

Certified that this is the bonafide record of work done


in Artificial Intelligence and Machine Learning Laboratory by Sri Jyolsna E.B
during the year 2024

Internal Examinar Staff-in-Charge

External Examinar Head of Section


Page |3

INDEX

Sl No: NAME OF EXPERIMENT DATE PAGE INITIAL OF


No : TEACHER
01. SIMPLE CALCULATOR 04

02. ODD OR EVEN 06

03. POSITIVE, NEGATIVE OR ZERO 08

04. LEAP YEAR OR NOT 10

05. AMSTRONG OR NOT 12

06. FACTORIAL 14

07. PRINT EVEN NUMBERS 16

08. PRIME OR NOT 18

09. SUM OF LIST 20

10. STUDENT TUPLE 22

11. EMPLOYEE DICTIONARY 24

12. OCCURANCE OF A CHARACTER 27

13. PALINDROME OR NOT 29

14. SUM USING FUNCTION 31

15. SIMPLE INTEREST 33

16. CLASS EMPLOYEE 35

17. CLASS STUDENT 38

18. EXCEPTIO HANDLING 42

19. SUM OF MATRICES 45

20. PREPROCESSING DATA 47

21. LINEAR REGREASSION 51

22. MULTIVARIATE LINERAR REGRESSION USING 53


JUPYTER LAB

23. LAST COIN STANDING 56

24. TIC TAC TOE 59

25. OPEN ENDED PROJECT 65


Page |4

Experiment No : 01
Date :

SIMPLE CALCULATOR

AIM :
Develop a python program for a simple calculator.

PROGRAM :
a = int7(input("Enter the first number:"))
b = int(input("Enter the second number:"))
print("1.Addition 2.Subtraction 3.Division 4.Multiplication 5.Modulus 6.Exit:")
while True:
c = int(input("Enter option:"))
if c == 1:
r=a+b
elif c == 2:
r=a-b
elif c == 3:
r=a/b
elif c == 4:
r=a*b
elif c == 5:
r=a%b
elif c == 6:
break
print("Result =", r)
Page |5

OUTPUT :
Enter the first number:2
Enter the second number:4
1.Addition 2.Subtraction 3.Division 4.Multiplication 5.Modulus 6.Exit:
Enter option:1
Result = 6
Enter option:4
Result = 8
Enter option:2
Result = -2
Enter option:3
Result = 0.5
Enter option:5
Result = 2
Enter option:6

RESULT :
Program successfully executed and output obtained.
Page |6

Experiment No : 02
Date :

ODD OR EVEN

AIM :
Develop a program to enter time in minutes and check whether it is odd or
even using if else.

PROGRAM :
m = int(input("Enter Number:"))
if m % 2 == 0:
print("Number is even.")
else:
print("Number is odd.")
Page |7

OUTPUT :
Enter Number:48
Number is even.

Enter Number:35
Number is odd.

RESULT :
Program successfully executed and output obtained.
Page |8

Experiment No : 03
Date :

POSITIVE, NEGATIVE OR ZERO

AIM :

Develop a program to check whether the given number positive, negative or


zero using nested if.

PROGRAM :

a = int(input("Enter the number:"))


if a >= 0:
if a == 0:
print("The number is zero")
else:
print("The number is positive")
else:
print("The number is negative.")
Page |9

OUTPUT :

Enter the number:45


The number is positive

Enter the number:0


The number is zero

Enter the number:-3


The number is negative.

RESULT :
Program successfully executed and output obtained.
P a g e | 10

Experiment No : 04
Date :

LEAP YEAR OR NOT

AIM :
Develop a program check whether the given year is leap year or not using
‘ifelif’ ladder.

PROGRAM :
y = int(input("Enter the year:"))
if y % 4 == 0 and (y % 100 != 0 or y % 400 == 0):
print("The year is a leap year")
else:
print("The year is not a leap year")
P a g e | 11

OUTPUT :
Enter the year:2024
The year is a leap year

Enter the year:2023


The year is not a leap year

RESULT :
Program successfully executed and output obtained.
P a g e | 12

Experiment No : 05
Date :

AMSTRONG OR NOT

AIM :
Develop a program to check whether the given number is amstrong or not
using while loop.

PROGRAM :
n = int(input("Enter the number:"))
t=n
s=0
while t > 0:
r = t % 10
s = s + r*r*r
t = t // 10
if n == s:
print("The number is an Armstrong number")
else:
print("The number is not an Armstrong number")
P a g e | 13

OUTPUT :
Enter the number:123
The number is not an Armstrong number

Enter the number:153


The number is an Armstrong number

RESULT :
Program successfully executed and output obtained.
P a g e | 14

Experiment No : 06
Date :

FACTORIAL

AIM :
Develop a program to find the factorial of a number using while loop.

PROGRAM :
n = int(input("Enter the number:"))
f=1
while n >= 1:
f=f*n
n=n-1
print("Factorial =", f)
P a g e | 15

OUTPUT :
Enter the number:4
Factorial = 24

RESULT :
Program successfully executed and output obtained.
P a g e | 16

Experiment No : 07
Date :

PRINT EVEN NUMBERS

AIM :
Develop a program to print even numbers from one to hundred using for
loop.

PROGRAM :
print("The even numbers from 1 to 100 are:")
for i in range(1, 100 + 1):
if i % 2 == 0:
print(i)
P a g e | 17

OUTPUT :
The even numbers from 1 to 100 are:
2
4
6
8
.
.
.
.
.
.
96
98
100

RESULT :
Program successfully executed and output obtained.
P a g e | 18

Experiment No : 08
Date :

PRIME OR NOT

AIM :
Develop a program to check whether the given number is prime or not and
display the factors of the number using for loop.

PROJECT :
num = int(input("Enter a number: "))
if num <= 1:
print("Not a prime number")
else:
prime = 1
for i in range(2, num):
if num % i == 0:
prime = 0
break
if prime == 1:
print(f"{num} is a prime number")
else:
print(f"{num} is not a prime number")
print(f"Factors of {num} are:")
for i in range(1, num + 1):
if num % i == 0:
print(i)
P a g e | 19

OUTPUT :
Enter a number: 48
48 is not a prime number
Factors of 48 are:
1
2
3
4
6
8
12
16
24
48

Enter a number: 53
53 is a prime number
Factors of 53 are:
1
53

RESULT :
Program successfully executed and output obtained.
P a g e | 20

Experiment No : 09
Date :

SUM OF LIST

AIM :
Develop a program to find the sum of elements in a list.

PROGRAM :
my_list = [1, 2, 3, 4, 5]
print('The list:', my_list)
total_sum = 0
i=0
while i < len(my_list):
total_sum = total_sum + my_list[i]
i=i+1
print('Sum =', total_sum)
P a g e | 21

OUTPUT :
The list: [1, 2, 3, 4, 5]
Sum = 15

RESULT :
Program successfully executed and output obtained.
P a g e | 22

Experiment No : 10
Date :

STUDENT TUPLE
AIM :
Develop a program to enter the name of five students and display alternate
names and convert tuple to list, sort in the alphabetical order and convert to
tuple.

PROGRAM :
name = ("ammu", "kummu", "vimmu", "chimmu", "tummu")
print("The tuple:", name)
print("Alternate names:")
for i in range(0, len(name), 2):
print(name[i])
name_list = list(name)
print("The list:", name_list)
name_list.sort()
print("Sorted list:", name_list)
name = tuple(name_list)
print("The tuple:", name)
print(type(name))
P a g e | 23

OUTPUT :
The tuple: ('ammu', 'kummu', 'vimmu', 'chimmu', 'tummu')
Alternate names:
ammu
vimmu
tummu
The list: ['ammu', 'kummu', 'vimmu', 'chimmu', 'tummu']
Sorted list: ['ammu', 'chimmu', 'kummu', 'tummu', 'vimmu']
The tuple: ('ammu', 'chimmu', 'kummu', 'tummu', 'vimmu')
<class 'tuple'>

RESULT :
Program successfully executed and output obtained.
P a g e | 24

Experiment No : 11
Date :

EMPLOYEE DICTIONARY

AIM :
Develop a program to enter the details of 5 employees into a dictionary.

PROGRAM :
employee_details = {}
for i in range(1, 6):
print(f"Enter details for Employee {i}:")
name = input("Name: ")
age = input("Age: ")
position = input("Position: ")
salary = input("Salary: ")
employee = {
'Name': name,
'Age': age,
'Position': position,
'Salary': salary
}
employee_details[f'Employee {i}'] = employee
print("\nEmployee Details:")
for employee, details in employee_details.items():
print(employee, details)
P a g e | 25

OUTPUT :
Enter details for Employee 1:
Name: Jobook
Age: 19
Position: Web Designer
Salary: 50000
Enter details for Employee 2:
Name: James
Age: 25
Position: Web Developer
Salary: 30000
Enter details for Employee 3:
Name: Jacob
Age: 35
Position: Manager
Salary: 38760
Enter details for Employee 4:
Name: Jason
Age: 32
Position: Software Developer
Salary: 60000
Enter details for Employee 5:
Name: John
Age: 31
Position: Backend Programmer
Salary: 70000
P a g e | 26

Employee Details:
Employee 1 {'Name': 'Jobook', 'Age': '19', 'Position': 'Web Designer ', 'Salary':
'50000'}
Employee 2 {'Name': 'James ', 'Age': '25', 'Position': 'Web Developer ', 'Salary':
'30000'}
Employee 3 {'Name': 'Jacob', 'Age': '35', 'Position': 'Manager', 'Salary': '38760'}
Employee 4 {'Name': 'Jason', 'Age': '32', 'Position': 'Software Developer ',
'Salary': '60000'}
Employee 5 {'Name': 'John', 'Age': '31', 'Position': 'Backend Programmer ',
'Salary': '70000'}

RESULT :
Program successfully executed and output obtain.
P a g e | 27

Experiment No : 12
Date :

OCCURRENCE OF A CHARACTER

AIM :
Develop a program in python to count the occurrence of a particular
character in a string.

PROGRAM :
a = input('Enter the string in lowercase: ')
n = input('Enter the character to be counted: ')
f=0
for char in a:
if char == n:
f += 1
print(f"{n} occurred {f} times.")
P a g e | 28

OUTPUT:
Enter the string in lowercase: ididsomethingbad
Enter the character to be counted: i
i occurred 3 times.

RESULT :
Program successfully executed and output obtain.
P a g e | 29

Experiment No : 13
Date :

PALINDROME OR NOT

AIM :
Develop a program to check whether the given string is palindrome or not.

PROGRAM :
pal = input('Enter the string in lowercase: ')
print(pal)
is_palindrome = True
j = len(pal) - 1
for i in range(len(pal)):
if pal[i] != pal[j]:
is_palindrome = False
break
j -= 1
if is_palindrome:
print('The word is Palindrome')
else:
print('The word is not Palindrome')
P a g e | 30

OUTPUT:
Enter the string in lowercase: funny
funny
The word is not Palindrome

Enter the string in lowercase: malayalam


malayalam
The word is Palindrome

RESULT :
Program successfully executed and output obtain.
P a g e | 31

Experiment No : 14
Date :

SUM USING FUNCTION

AIM :
Develop a program to add two numbers using function

PROGRAM :
def sum(a, b):
s=a+b
return s
a = int(input('Enter the first number:'))
b = int(input('Enter the second number:'))
print('Sum = ', sum(a, b))
P a g e | 32

OUTPUT:
Enter the first number:34
Enter the second number:54
Sum = 88

RESULT :
Program successfully executed and output obtain.
P a g e | 33

Experiment No : 15
Date :

SIMPLE INTEREST

AIM :
Develop a program to calculate simple interest using function.

PROGRAM :
def si(p, r, t):
si = (p * r * t) / 100
return si
p = int(input('Enter the principle amount:'))
r = int(input('Enter the rate of interest:'))
t = int(input('Enter the time period:'))
print("Simple Interest =", si(p, r, t))
P a g e | 34

OUTPUT:
Enter the principle amount:4500
Enter the rate of interest:8
Enter the time period:4
Simple Interest = 1440.0

RESULT :
Program successfully executed and output obtain.
P a g e | 35

Experiment No : 16
Date :

CLASS EMPLOYEE
AIM :
Develop a program using class in python to enter the details of an employee
and calculate the gross salary(using set data).
PROGRAM :
class Employee:
def set_data(self):
self.name = input("Enter Name: ")
self.id = int(input("Enter ID: "))
self.bp = float(input("Enter Basic Pay: "))
self.da = self.bp * 0.10
self.hra = self.bp * 0.05

def display(self):
print("Name:", self.name)
print("ID:", self.id)
print("Basic Pay:", self.bp)
print("Dearness Allowance :", self.da)
print("House Rent Allowance :", self.hra)

def salary(self):
gross_salary = self.bp + self.da + self.hra
print("Total Gross Salary:", gross_salary)
P a g e | 36

e1 = Employee()
e1.set_data()
e1.display()
e1.salary()
P a g e | 37

OUTPUT :
Enter Name: aleena
Enter ID: 2001
Enter Basic Pay: 20000
Name: aleena
ID: 2001
Basic Pay: 20000.0
Dearness Allowance : 2000.0
House Rent Allowance : 1000.0
Total Gross Salary: 23000.0

RESULT :
Program successfully executed and output obtain.
P a g e | 38

Experiment No : 17
Date :

CLASS STUDENT

AIM :
Develop a program using class in python to enter the details of students and
calculate their grade (using init).

PROGRAM :
class Student:
def __init__(self, name, regno, mark1, mark2, mark3):
self.name = name
self.regno = regno
self.mark1 = mark1
self.mark2 = mark2
self.mark3 = mark3
def calculate_grade(self):
total_marks = self.mark1 + self.mark2 + self.mark3
percentage = (total_marks / 300) * 100
print("Total marks out of 300:", total_marks)
if self.mark1 < 30 or self.mark2 < 30 or self.mark3 < 30:
print("Grade: F")
elif percentage >= 90:
print("Grade: S")
elif percentage >= 80:
P a g e | 39

print("Grade: A")
elif percentage >= 70:
print("Grade: B")
elif percentage >= 60:
print("Grade: C")
elif percentage >= 50:
print("Grade: D")
elif percentage >= 40:
print("Grade: E")
else:
print("Grade: F")
def display_student_details(self):
print("Student Details:")
print("Name:", self.name)
print("Register Number:", self.regno)
print("Marks of first subject:", self.mark1)
print("Marks of second subject:", self.mark2)
print("Marks of third subject:", self.mark3)
self.calculate_grade()
n = int(input("Enter the count of students: "))
students = []
for i in range(n):
name = input("Name: ")
id = int(input('Roll No: '))
m1 = int(input('Enter the first mark out of 100: '))
m2 = int(input('Enter the second mark out of 100: '))
P a g e | 40

m3 = int(input('Enter the third mark out of 100: '))


student = Student(name, id, m1, m2, m3)
students.append(student)
student.display_student_details()
P a g e | 41

OUTPUT:
Enter the count of students: 3
Name: Jobook
Roll No: 32
Enter the first mark out of 100: 89
Enter the second mark out of 100: 87
Enter the third mark out of 100: 98
Student Details:
Name: Jobook
Register Number: 32
Marks of first subject: 89
Marks of second subject: 87
Marks of third subject: 98
Total marks out of 300: 274
Grade: S
Name: Alia
Roll No: 05
Enter the first mark out of 100: 34
Enter the second mark out of 100: 65
Enter the third mark out of 100: 45
Student Details:
Name: Alia
Register Number: 5
Marks of first subject: 34
Marks of second subject: 65
Marks of third subject: 45
P a g e | 42

Total marks out of 300: 144


Grade: E
Name: RaceIly
Roll No: 29
Enter the first mark out of 100: 87
Enter the second mark out of 100: 78
Enter the third mark out of 100: 98
Student Details:
Name: RaceIly
Register Number: 29
Marks of first subject: 87
Marks of second subject: 78
Marks of third subject: 98
Total marks out of 300: 263
Grade: A

RESULT :
Program successfully executed and output obtain.
P a g e | 43

Experiment No : 18
Date :

EXCEPTION HANDLING
AIM :
Develop a program for exception handling in python.

PROGRAM :
# program to implement exception handling.
try:
a=int(input("Enter First no:"))
b=int(input("Enter Second no:"))
c=a/b
print("Quotient=",c)
except ZeroDivisionError:
print("Denominator is 0")
P a g e | 44

OUTPUT :

∙ Enter First no:2


Enter Second no:4
Quotient= 0.5
∙ Enter First no:3
Enter Second no:0
Denominator is 0

RESULT :

Successfully executed the program and obtained the output.


P a g e | 45

Experiment No : 19
Date :

SUM OF MATRICES
AIM :
Develop a program to import a numpy array and add two matrices using
Jupyter notebook.

PROGRAM :
# program to implement numpy.
import numpy as np
od=np.array([[1,2,3,4,5]])
odt=np.array([[1,2,3,4,5]])
print("First array :",od)
print("Second array :",odt)
print('Adding two arrays')
for i in range (0,len(od)):
for j in range(0,len(odt)):
print('Sum of elements',od[i]+odt[i])
P a g e | 46

OUTPUT :

First array : [[1 2 3 4 5]]


Second array : [[1 2 3 4 5]]
Adding two arrays
Sum of elements [ 2 4 6 8 10]

RESULT :

Successfully executed the program and obtained the output.


P a g e | 47

Experiment No : 20
Date :

PREPROCESSING DATA
AIM :
Develop a program in python by importing pandas , matplot lib and read a
dataset and do various preprocessing also plot the dataset.

PROGRAM :
# program to implement preprocessing.
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from sklearn import preprocessing
input_data=np.array([[2.1,-1.9,5.5],[-1.5,2.4,3.5],[0.5,-7.9,5.6],[5.9,2.3,-5.8]])
print("Input data")

print(input_data)
print("Data preproccessed by Binarization")
data_binarized=preprocessing.Binarizer(threshold=0.5).transform(input_data
) print(data_binarized)

print("Data preproccessed by Mean removal")


print(input_data.mean(axis=0))
print(input_data.std(axis=0))
data_scaled=preprocessing.scale(input_data)
print(data_scaled.mean(axis=0))
print(data_scaled.std(axis=0))
P a g e | 48

print("Data preproccessed by SCALING- MIN MAX")


data_scaler_minmax=preprocessing.MinMaxScaler(feature_range=(0,1)
) data_scaled_minmax=data_scaler_minmax.fit_transform(input_data)
print(data_scaled_minmax)

print("Data preproccessed by L1 Normalization")


data_normalized_l1=preprocessing.normalize(input_data,norm='l1'
) print(data_normalized_l1)

print("Data preproccessed by L2 Normalization")


data_normalized_l2=preprocessing.normalize(input_data,norm='l2'
) print(data_normalized_l2)

import pandas as pd
dataset_path=(r"new.csv")
arr=pd.read_csv(dataset_path)
import matplotlib.pyplot as plt
x=arr['name']
y=arr['mark']
plt.plot(x,y)
plt.show()
plt.scatter(x,y)
x=[5,2,9,4,7]
y=[10,5,7,2,3]
plt.bar(x,y)
plt.show()
plt.hist(y)
plt.show()
P a g e | 49

OUTPUT :
Input data
[[ 2.1 -1.9 5.5]
[-1.5 2.4 3.5]
[ 0.5 -7.9 5.6]
[ 5.9 2.3 -5.8]]
Data preproccessed by Binarization
[[1. 0. 1.]
[0. 1. 1.]
[0. 0. 1.]
[1. 1. 0.]]
Data preproccessed by Mean removal
[ 1.75 -1.275 2.2 ]
[2.71431391 4.20022321 4.69414529]
[1.11022302e-16 0.00000000e+00 0.00000000e+00]
[1. 1. 1.]
Data preproccessed by SCALING- MIN MAX
[[0.48648649 0.58252427 0.99122807]
[0. 1. 0.81578947]
[0.27027027 0. 1. ]
[1. 0.99029126 0. ]]
Data preproccessed by L1 Normalization
[[ 0.22105263 -0.2 0.57894737]
[-0.2027027 0.32432432 0.47297297]
[ 0.03571429 -0.56428571 0.4 ]
[ 0.42142857 0.16428571 -0.41428571]]
Data preproccessed by L2 Normalization
P a g e | 50

[[ 0.33946114 -0.30713151 0.88906489]


[-0.33325106 0.53320169 0.7775858 ]
[ 0.05156558 -0.81473612 0.57753446]
[ 0.68706914 0.26784051 -0.6754239 ]]

RESULT :

Successfully executed the program and obtained the output.


P a g e | 51

Experiment No : 21
Date :

LINEAR REGRESSION
AIM :
Develop a program in python using linear regression to estimate the house
price if area is given using Jupyter notebook.

PROGRAM :
# program to implement linear regression.
import numpy as np
from sklearn import linear_model
import sklearn.metrics as sm
import matplotlib.pyplot as plt
import pandas as pd
datasetpath="Downloads/homeprices.csv"
tp=pd.read_csv(datasetpath)
print(tp.head)
from sklearn import linear_model
rg=linear_model.LinearRegression()
x=tp.drop('price',axis='columns')
print(x)
y=tp.price
print(y)
rg.fit(x,y)
rg.predict([[3500]])
P a g e | 52

OUTPUT :

<bound method NDFrame.head of area price


0 2600 550000
1 3000 565000
2 3200 610000
3 3600 680000
4 4000 725000>
area
0 2600
1 3000
2 3200
3 3600
4 4000
0 550000
1 565000
2 610000
3 680000
4 725000
Name: price, dtype: int64

array([655873.28767123])

RESULT :

Successfully executed the program and obtained the output.


P a g e | 53

Experiment No : 22
Date :

MULTIVARIATE
LINEAR REGRESSION USING JUPYTER LAB

AIM :
Develop a program in python using multivariate linear regression to estimate
the house price using Weka.

PROGRAM :
# program to implement multivariate linear regression.
import numpy as np
from sklearn import linear_model
import sklearn.metrics as sm
import matplotlib.pyplot as plt
import pandas as pd
dataset2_path='Downloads/homeprices2.csv'
pt=pd.read_csv(dataset2_path)
pt.head()
pt.info()
values={"bedrooms":1.0}
pt=pt.fillna(value=values)
x=pt.drop('price',axis='columns')
print(x)
P a g e | 54

y=pt.price
print(y)
regr=linear_model.LinearRegression()

regr.fit(x,y)
regr.predict([[2100,4,6]])[0]
P a g e | 55

OUTPUT :

RESULT :

Successfully executed the program and obtained the output.


P a g e | 56

Experiment No : 23
Date :

LAST COIN STANDING


AIM :
Demonstrate a Bot to Play Last Coin Standing using python.

PROGRAM :

import random
# Function to make a move for the bot
def bot_move(coins, max_coins):
# Implement your bot's strategy here
# For example, you can choose to make a random move
move = random.randint(1, max_coins)
# Ensure that the move is within the allowed range
move = min(move, coins)
return move

# Main game loop


def play_game():
coins = 15 # Set the initial number of coins
max_coins = 3 # Maximum number of coins a player can take in one
turn
P a g e | 57

while coins > 0:

print(f"Remaining coins: {coins}")

# Bot's move
bot_move_count = bot_move(coins, max_coins)
print(f"Bot takes {bot_move_count} coin(s).")
coins -= bot_move_count

if coins == 0:
print("Bot wins!")
break

# Human player's move (if you want to play against the bot)
player_move_count = int(input("Your turn: How many coins will you
take? "))

coins -= player_move_count

if coins == 0:
print("You win!")
break

if __name__ == "__main__":
play_game()
P a g e | 58

OUTPUT :

Remaining coins: 15
Bot takes 2 coin(s).
Your turn: How many coins will you take? 2
Remaining coins: 11
Bot takes 3 coin(s).
Your turn: How many coins will you take? 2
Remaining coins: 6
Bot takes 1 coin(s).
Your turn: How many coins will you take? 2
Remaining coins: 3
Bot takes 3 coin(s).
Bot wins!
:

RESULT :

Successfully executed the program and obtained the output.


P a g e | 59

Experiment No : 24
Date :

TIC TAC TOE


AIM :
Demonstrate a Bot to Play Tic Tac Toe using python.

PROGRAM :

board = [' '] * 10


computer = 'X'
human = 'O'

def display_board(board):
print(f'{board[1]} | {board[2]} | {board[3]}')
print(f'{board[4]} | {board[5]} | {board[6]}')
print(f'{board[7]} | {board[8]} | {board[9]}')
print('-' * 10)

def check_win():
if board[1] == board[2] == board[3] and board[1] != ' ':
return True
elif board[4] == board[5] == board[6] and board[4] != ' ':
return True
elif board[7] == board[8] == board[9] and board[7] != ' ':
return True
elif board[1] == board[4] == board[7] and board[1] != ' ':
return True
P a g e | 60

elif board[2] == board[5] == board[8] and board[2] != ' ':


return True
elif board[3] == board[6] == board[9] and board[3] != ' ':
return True
elif board[1] == board[5] == board[9] and board[1] != ' ':

return True
elif board[7] == board[5] == board[3] and board[7] != ' ':
return True
else:
return False

def is_win(letter):
if board[1] == board[2] == board[3] and board[1] == letter:
return True
elif board[4] == board[5] == board[6] and board[4] == letter:
return True
elif board[7] == board[8] == board[9] and board[7] == letter:
return True
elif board[1] == board[4] == board[7] and board[1] == letter:
return True
elif board[2] == board[5] == board[8] and board[2] == letter:
return True
elif board[3] == board[6] == board[9] and board[3] == letter:
return True
elif board[1] == board[5] == board[9] and board[1] == letter:
return True
elif board[7] == board[5] == board[3] and board[7] == letter:
return True
else:
P a g e | 61

return False

def check_draw():
if board.count(' ') < 2:
return True
else:
return False

def is_available(pos):
return True if board[pos] == ' ' else False

def insert(letter, pos):


if is_available(pos):

board[pos] = letter
display_board(board)
if check_win():
if letter == 'X':
print("Computer Wins")
exit()
else:
print("Human wins")
exit()
if check_draw():
print("Draw")
exit()
else:
pos = int(input("Not Free! Please re-enter a position"))
insert(letter, pos)
P a g e | 62

def human_move(letter):
pos = int(input("Enter the position to insert:"))
insert(letter, pos)

def computer_move(letter):
best_score = -100
best_pos = 0
for index in range(1, len(board)):
if is_available(index):
board[index] = letter
score = minimax(board, False)
board[index] = " "
if score > best_score:
best_score = score
best_pos = index
insert(letter, best_pos)
return

def minimax(board, is_maximizing):


if is_win(computer):
return 10

elif is_win(human):
return -10
elif check_draw():
return 0
if is_maximizing: # computer's turn (X)
best_score = -100
P a g e | 63

for index in range(1, len(board)):


if is_available(index):
board[index] = computer
score = minimax(board, False)
board[index] = " "
best_score = max(best_score, score)
return best_score
else: # human's turn (O)
best_score = 100
for index in range(1, len(board)):
if is_available(index):
board[index] = human
score = minimax(board, True)
board[index] = " "
best_score = min(best_score, score)
return best_score

# Main loop
while not check_win():
display_board(board)
computer_move(computer)
human_move(human)
P a g e | 64

OUTPUT :
|| X|O| Enter the position to
in sert: 6
|| X||
X|O|O
|| ||
X|X|O
---------- ----------
||
X|| Enter the position to ----------
in sert: 3
|| X|O|O
X|O|O
|| X|X|O
X||
---------- ||
||
Enter the position to ----------
in sert: 1 ----------
X|O|O
Not Free! Please re- X|O|O
ent er a position 2 X|X|O
X||
X|O| X||
||
|| ----------
----------
|| Computer Wins
X|O|O
---------- Enter the position to
X|X| in sert: 8
X|O|
|| X|O|O
||
---------- X|X|O
||
---------- X|O|
----------
Human wins

RESULT :

Successfully executed the


program and obtained the
output.
P a g e | 65

OPEN ENDED PROJECT


P a g e | 66

Date:

PRICE OF AN ITEM PREDICTED BASED ON IT’S WEIGHT

Aim:-
Develop a program to predict the price of an item based on
its weight using simple linear regression model.

Output:-
P a g e | 67

RESULT:-
Program successfully executed and output obtained.

You might also like