Department of Computer Engineering: Fundamentals of Artificial Intelligence and Machine Learning Lab

Scarica in formato pdf o txt
Scarica in formato pdf o txt
Sei sulla pagina 1di 47

++

DEPARTMENT OF COMPUTER
ENGINEERING

FUNDAMENTALS OF ARTIFICIAL INTELLIGENCE AND


MACHINE LEARNING LAB

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

# To get year (integer input) from the user


year = int(input("Enter a year: "))

# divided by 100 means century year (ending with 00)


# century year divided by 400 is leap year
if (year % 400 == 0) and (year % 100 == 0):
print("{0} is a leap year".format(year))

# not divided by 100 means not a century year


# year divided by 4 is a leap year
elif (year % 4 ==0) and (year % 100 != 0):
print("{0} is a leap year".format(year))

# 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]

# using sum() function


total = sum(list1)

# printing total value


print("Sum of all elements in given list: ", total)

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

print("\nFactorial =", fact)

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

# iterating each number in list


for num in range(start, end + 1):

# 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

• Read two strings str1 and str2


Str1 = "Hello"
print(str1)

str2 = "World."
print(str2)
• Write a python program to find the length of string
print(len(str1))
print(len(str2))

• Write a python program to concatenate two strings


Str3=str1 +str2
Print(str3)

• Write a python program to Repeat str1 n times


Str1 = "Hello"
n=4

output = Str1 * 4
print(output)

5.Write a python program to print a slice of str1


print(Str1[:3])

6.Write a python program to check a particular letter is not in str1


if "He" in Str1:
print ("Yes, String found")
else :
print ("No, String not found")

7.Write a python program to iterate over the elements of the strings


string_to_iterate = "Data Science"
for char in string_to_iterate:
print(char)

8.Write a python program to print letters starting from index 4, ending at index 11

str ="Hello world hii!"


# slicing using indexing sequence
print(str[3:12])

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

txt = "Hello World"[::-1]


print(txt)

• Write a python program to convert a string to uppercase


message = 'python is fun'
# convert message to uppercase
print(message.upper())

• Write python program To count the occurrence of a character in a string.

my_string = "Hello World"


char_count = my_string.count('l')
print(char_count)

• Write a python program To split a string into a list of words

txt = "welcome to the jungle"


x = txt.split()
print(x)

5. Write python program To replace a substring in a string

string = "Hello World"


new_string = string.replace("Hello", "Hi")

print(new_string)

6. Write a python program To find the index of a substring in a string

string = "Hello World!"


substring = "World"
index = string.find(substring)
print(index)

• Write python program To print all vowels in a word


word = input("Write your word here: ")
print(word)

for letter in word:


if letter == 'a'or letter == 'e'or letter == 'i'or letter == 'o'or letter == 'u':
print(letter)
OUTPUT

• 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

1. Write a python program to access elements in lists

list = ["Bob", "Mark", "Deepak", "Harry", "Ivaan"]


print(list[0][1])
print(list[1][1])

print(list[2][3])
print(list[3][0])
print(list[4][4])

2.Modifying elements in lists

list = ["Bob", "Mark", "Deepak", "Harry", "Ivaan"]


#modify
list[2] = 'Mona'

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)

5.Find the index of an element

list1 = ["apple", "banana", "cherry"]


print(list1.index('banana'))

6.sorting in list

numbers = [1, 3, 4, 2]
numbers.sort()
print(numbers)

7.Merging list

list1 = ["apple", "banana", "cherry"]


list2 = ["mango", "pineapple", "papaya"]
list3=list1+list2
print(list3)

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

• Write a python program for Accessing elements in tuples


tuple = ("apple", "banana", "cherry")
print(tuple)
print(tuple[1])
• Multiplication of tuples
tuple_1 = (23, 45, 12, 56, 78)
tuple_2 = (89, 41, 76, 0, 11)

print("The first tuple is : ")


print(tuple_1)
print("The second tuple is : ")
print(tuple_2)

result = tuple(elem_1 * elem_2 for elem_1, elem_2 inzip(tuple_1,tuple_2))

print("The multiplied tuple is : ")


print(result)

• Unpacking of tuples
fruits = ("apple", "banana", "cherry")

(green, yellow, red) = fruits

print(green)
print(yellow)
print(red)

• Checking length and presence of tuple elements


Tuple =( 1, 0, 4, 2, 5, 6, 7, 5)
print(len(Tuple))
print(len(fruits))

• Counting tuple elements


value = (1, 3, 7, 8, 7, 5, 7, 6, 8, 5)
value.count(7)
• Converting tuple to a list
Tuple = (123, 'xyz', 'zara', 'abc');
List = list(Tuple)
print("List elements : ", List)
OUTPUT:
• ('apple', 'banana', 'cherry')
banana
• The first tuple is :
(23, 45, 12, 56, 78)
The second tuple is :
(89, 41, 76, 0, 11)
The multiplied tuple is :
(2047, 1845, 912, 0, 858)
3. banana
apple
cherry
4. 8
5
5. 3
6. List elements : [123, 'xyz', 'zara', 'abc']

RESULT:
The program ran successfully and obtained desired output

EXPERIMENT 9:

DICTIONARY OPERATIONS
AIM:

• Write a python program to create a dictionary

Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}


print(Dict)
• Write a python program FOR Accessing and modifying elements in dictionary
dict = {'hari': 1, 'dita': 2}

# original dictionary
print("initial dictionary-", dict)
# changing the key value from 2 to 4
dict['dita'] = 4

# dictionary after update


print("dictionary after modification-", dict)

• Checking presence and length of dictionary elements


dict1 ={'Name':'Steve', 'Age':30, 'Designation':'Programmer'}

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

STUDENT NAME AND GRADES


AIM
To create a dictionary of student name and their corresponding grades

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

• Write a program to add two numbers using python function


defadd_numbers(num1, num2):
sum = num1 + num2
print('Sum: ',sum)
add_numbers(5, 4)

• print the square root of number using function


# function definition
deffind_square(num):
result = num * num
return result
# function call
square = find_square(3)
print('Square:',square)

• Program to find odd or even by using function


defevenOdd(x):
if (x % 2 == 0):
print("even")
else:
print("odd")
# Driver code to call the function
evenOdd(2)
evenOdd(3)

• swapping numbers using function


defswap(x,y):
print("Before swapping a :",x)
print("Before swapping b :",y)
#logic to swap without using third variable
x,y=y,x
return x,y
a=int(input("Enter value : "))
b=int(input("Enter value : "))
a,b=swap(a,b)
print("After swapping a becomes :",a)
print("After swapping b becomes :",b)
OUTPUT
1.Sum: 9
2. Square: 9
3.even
Odd
4. Enter value : 12
Enter value : 15
Before swapping a : 12
Before swapping b : 15
After swapping a becomes : 15
After swapping b becomes : 12

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

PROGRAMS USING PACKAGES

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)

**programs using numpy package


import numpy as np
#print 1D array
a = np.array([1,2,3]) # Calling the array function

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]

# plotting the points


plt.plot(x, y)

# naming the x axis


plt.xlabel('x - axis')
# naming the y axis
plt.ylabel('y - axis')

# giving a title to my graph


plt.title('My first graph!')

# function to show the plot


plt.show()
RESULT:
The program ran successfully and obtained desired output.

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)

# create object of Room class


study_room = Room()

# assign values to all the attributes


study_room.length = 42.5
study_room.breadth = 30.8

# access method inside class


study_room.calculate_area()

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:

Waikato Environment for Knowledge Analysis (Weka), developed at the University of


Waikato, New Zealand, is free software licensed under the GNU General Public License
Weka contains a collection of visualization tools and algorithms for data analysis and predictive
modeling, together with graphical user interfaces for easy access to these functions. This
original version was primarily designed as a tool for analyzing data from agricultural
domains,but the more recent fully Java-based version (Weka 3), for which development started
in 1997, is now used in many different application areas, in particular for educational purposes
and research.
Advantages of Weka include:
• Free availability under the GNU General Public License.
• Portability, since it is fully implemented in the Java programming language and thus rans
on almost any modern computing platform.
• A comprehensive collection of data preprocessing and modeling techniques.
• Ease of use due to its graphical user interfaces.
Weka supports several standard datamining tasks, more specifically, data
preprocessing, clustering, classification, regression, visualization, and feature selection. Input to
Weka is expected to be formatted according the Attribute-Relational File Format and with the
filename bearing the .arff extension. All of Weka's techniques are predicated on the assumption
that the data is available as one flat file or relation, where each data point is described by a fixed
number of attributes (normally, numeric or nominal attributes, but some other attribute types are
also supported). It is not capable of multi-relational data mining, but there is separate software
for converting a collection of linked database tables into a single table that is suitable for
processing using Weka.Another important area that is currently not covered by the algorithms
included in the Weka distribution is sequence modeling.
Basic WEKA system deployment
The basic WEKA deployment model involves the creation of a shareable filesystem to be used
by the application servers. This requires the installation of WEKA client software which
implements a POSIX filesystem driver on each application server intended to access data. This
filesystem driver enables each of the application servers to access the WEKA system as if it is a
local drive, perceiving the WEKA system as a local attached filesystem device while it is
actually shared among multiple application servers.
The file services are implemented by a group of backend servers ranning the WEKA software
and fully dedicated to the WEKA system. SSD drives for storing the data are installed on these
servers. The resultant storage system is scalable to hundreds of backends and thousands of
clients.
The servers in a WEKA system are members of a cluster. A server includes multiple containers
ranning software instances called processes that communicate with each other to provide
storage services in the cluster.

The processes are dedicated to managing different functions as follows:


• Drive processes for SSD drives and IO to drives. Each drive process requires a dedicated
core.
• Compute processes for filesystems, cluster-level functions, and IO from clients. Each
compute process requires a dedicated core.
• Frontend processes for POSIX client access and sending IO to the compute and drive
processes. Each frontend process requires a dedicated core.
• A management process for managing the overall cluster. The management process does
not require a dedicated core.
DOWNLOAD AND INSTALL WEKA SOFTWARE

Follow the below steps to install Weka on Windows:


Step 1: Visit this website using any web browser. Click on Free Download.
Step 2: It will redirect to a new webpage, click on Start Download. Downloading of the
executable file will start shortly. It is a big 118 MB file that will take some minutes.
Step 3: Now check for the executable file in downloads in your system and ran it.
Step 4: It will prompt confirmation to make changes to your system. Click on Yes.
Step 5: Setup screen will appear, click on Next.
Step 6: The next screen will be of License Agreement, click on I Agree.
Step 7: Next screen is of choosing components, all components are already marked so don’t
change anything just click on the Install button.
Step 8: The next screen will be of installing location so choose the drive which will have
sufficient memory space for installation. It needed a memory space of 301 MB.
Step 9: Next screen will be of choosing the Start menu folder so don’t do anything just click
on Install Button.
Step 11: Click on the Next button after the installation process is complete.
Step 12: Click on Finish to finish the installation process.
Step 13: Weka is successfully installed on the system and an icon is created on the desktop.
Step 14: Ran the software and see the interface.

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:

A. Load CSV Files in the Weka Explorer


1. Start the Weka GUI Chooser.
2. Launch the Weka Explorer by clicking the “Explorer” button
3. Click the “Open file…” button.
4. Navigate to your current working directory. Change the “Files of Type” to “CSV data files
(*.csv)”. Select your file and click the “Open” button.

B. Loading of data from url


1.Start the weka GUI chooser
2.Launch the Weka Explorer by clicking the “Explorer” button
3.Load url in weka explorer
4.open the file from a public URL
5. The Explorer will load the data from the remote site into its environment.

C. Loading of data from DB


1.Start the weka GUI chooser
2.Launch the Weka Explorer by clicking the “Explorer” button.
3. Once you click on the Open DB ... button
4.Set the connection string to your database
5. set up the query for data selection
6.process the query and load the selected records in WEKA

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

Load data using pandas


df = pd.read_csv('employee.csv')
df

df.info()
Checking any null values in dataset
df.isnull().any()

Drop unneccesary columns


cols = ['grade']
df = df.drop(cols, axis=1)

Fill missing values


df.bfill()
Label encoding the dataset
from sklearn import preprocessing
from sklearn.preprocessing import LabelEncoder
le = preprocessing.LabelEncoder()
y=['name','age','income','gender','department','performance_score']
for i in y:
df[i]=le.fit_transform(df[i])

Scaling the dataset


from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
w=scaler.fit_transform(df)
w
RESULT:
The program ran successfully and obtained desired output.

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:

CLASSIFIERS USING PYTHON


Write a python program to implement classifiers for gender prediction..

PROGRAM:

#{height, weights, shoe size}


X
=[[190,70,44],[166,65,45],[190,90,47],[175,64,39],[171,75,40],[177,80,42],[160,60,38],[144,54
,37]]
Y = ['male','male','male','male','female','female','female','female']

#Predict for this vector (height, wieghts, shoe size)


P = [[190,80,46]]

#{Decision Tree Model}


from sklearn.tree import DecisionTreeClassifier
clf = DecisionTreeClassifier()
clf = clf.fit(X,Y)
print ("\n1) Using Decision Tree Prediction is " + str(clf.predict(P)))

#{K Neighbors Classifier}

from sklearn.neighbors import KNeighborsClassifier


knn = KNeighborsClassifier()
knn.fit(X,Y)
print("2) Using K Neighbors Classifier Prediction is " +str(knn.predict(P)))

#{Random forest Model}


from sklearn.ensemble import RandomForestClassifier
rfor = RandomForestClassifier()
rfor.fit(X,Y)
print ("3) Using RandomForestClassifier Prediction is " + str(rfor.predict(P)) +"\n")

#{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']

2) Using K Neighbors Classifier Prediction is ['male']


3) Using Random Forest Classifier Prediction is ['female']

4) Using SVC 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)

defremove_coins(self, num_coins_to_remove, player):


self.num_coins -= num_coins_to_remove
print(f"{player} removes {num_coins_to_remove} coins.")

if__name__ == "__main__":
game = LastCoinStanding()
game.play()

OUTPUT:
Welcome to Last Coin Standing!

Coins left in the pile: 25


Enter the number of coins to remove (1-4): 5
Invalid move. Please choose between 1 and 4 coins.
Enter the number of coins to remove (1-4): 2
Human removes 2 coins.
Bot removes 4 coins.

Coins left in the pile: 19


Enter the number of coins to remove (1-4): 3
Human removes 3 coins.
Bot removes 1 coins.

Coins left in the pile: 15


Enter the number of coins to remove (1-4): 5
Invalid move. Please choose between 1 and 4 coins.
Enter the number of coins to remove (1-4): 1
Human removes 1 coins.
Bot removes 2 coins.

Coins left in the pile: 12


Enter the number of coins to remove (1-4): 2
Human removes 2 coins.
Bot removes 3 coins.
Coins left in the pile: 7
Enter the number of coins to remove (1-4): 2
Human removes 2 coins.
Bot removes 2 coins.

Coins left in the pile: 3


Enter the number of coins to remove (1-4): 3
Human removes 3 coins.
Human wins!

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

# Function to display the Tic-Tac-Toe board


defdisplay_board(board):
for row in board:
print(" | ".join(row))
print("-" * 9)

# Function to check if a player has won


defcheck_win(board, player):
for row in board:
ifall(cell == player for cell in row):
returnTrue

for col inrange(3):


ifall(row[col] == player for row in board):
returnTrue
ifall(board[i][i] == player for i inrange(3)) orall(board[i][2 - i] == player for i inrange(3)):
returnTrue
returnFalse
# Function to check if the board is full
defis_board_full(board):
returnall(cell != " "for row in board for cell in row)

# Function to make the bot's move using minimax algorithm


defbot_move(board):
best_score = float("-inf")
best_move = None

for i inrange(3):
for j inrange(3):
if board[i][j] == " ":
board[i][j] = "O"
score = minimax(board, 0, False)
board[i][j] = " "

if score > best_score:


best_score = score
best_move = (i, j)

return best_move

defminimax(board, depth, is_maximizing):


scores = {"X": -1, "O": 1, "tie": 0}

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

# Main game loop


defplay_game():
board = [[" "for _ inrange(3)] for _ inrange(3)]
current_player = "X"

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

current_player = "X"if current_player == "O"else"O"


# Start the game
play_game()

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

# Generate a random number between 1 and 100


secret_number = random.randint(1, 100)
attempts = 0

print("Welcome to the Number Guessing Game!")


print("I'm thinking of a number between 1 and 100.")

whileTrue:
try:
# Get the player's guess
guess = int(input("Guess the number: "))
attempts += 1

# Check if the guess is correct


if guess == secret_number:
print(f"Congratulations! You guessed the number {secret_number} in {attempts} attempts.")
break
elif guess < secret_number:
print("Try a higher number.")
else:
print("Try a lower number.")

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.

Potrebbero piacerti anche