0% found this document useful (0 votes)
3 views

DML

The document contains multiple Python programs demonstrating various programming concepts such as generating Fibonacci series, creating functions with arguments, calculating factorials using recursion, and manipulating lists and dictionaries. It also covers the use of mathematical operations on arrays, string functions, and random number generation. Each program includes user input and output examples to illustrate the functionality.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

DML

The document contains multiple Python programs demonstrating various programming concepts such as generating Fibonacci series, creating functions with arguments, calculating factorials using recursion, and manipulating lists and dictionaries. It also covers the use of mathematical operations on arrays, string functions, and random number generation. Each program includes user input and output examples to illustrate the functionality.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

PROGRAM 01

PROGRAM TO GENERATE FIBONACCI SERIES

#Program to generate fibonacci series


y=int(input("How many numbers of Fibonacci series to be printed: "))
a=0
b=1
print(a)
print(b)
for i in range(3,y+1):
c=a+b
a=b
b=c
print(c)
print("Thanks")
OUTPUT:

How many numbers of Fibonacci series to be printed: 8


0
1
1
2
3
5
8
13
Thanks
PROGRAM 02
PROGRAM TO CREATE FUNCTIONS WITH ARGUMENTS AND RETURNING VALUES

#Program to create functions with arguments and returning values


def square(side):
return side*side
def circle(r):
return (3.14*r*r)
def rectangle(l,b):
return (l*b)
def triangle(a,b,c):
s=(a+b+c)/2
return (((s-a)+(s-b)+(s-c))**0.5)
#Writing the main program and calling the functions
x=int(input("Enter your choice from 1 to 4: 1-triangle,2-square,3-circle,4-rectangle: "))
if x==1:
a,b,c=eval(input("Enter the three sides of the triangle: "))
ans=triangle(a,b,c)
elif x==2:
side=eval(input("Enter the length of the square: "))
ans=square(side)
elif x==3:
r=eval(input("Enter the radius of the circle: "))
ans=circle(r)
elif x==4:
l,b=eval(input("Enter the length and breadth of the rectangle: "))
ans=rectangle(l,b)
else:
print("Not a valid choice")
print("The area of the shape is: ",ans)
OUTPUT:

Enter your choice from 1 to 4: 1-triangle,2-square,3-circle,4-rectangle: 2


Enter the length of the square: 6
The area of the shape is: 36
PROGRAM 03
PROGRAM TO DETERMINE THE FACTORIAL OF A NUMBER USING RECURSIVE FUNCTION

#Program to create a recursive function


def fact(n):
if n==0:
return 1
else:
ans=n*fact(n-1)
return ans
#Calling the functions
x=int(input("Enter the number for which you want to compute factorial: "))
print("The factorial of",x,"is:",fact(x))
OUTPUT:

Enter the number for which you want to compute factorial: 14


The factorial of 14 is: 87178291200
PROGRAM 04
PROGRAM FOR DEMOSTRATING FUNCTIONS FOR LIST

#Program for demonstrating functions on lists


newlist=[10,20,30,40,30,30,50,60,70,30]
#The count() function returns the number of times a given element appears in the list
print("The number of times 30 occured in the list is: ",newlist.count(30))
#The index() function returns the lowest index of a given element within the list.Produces an error if the
element does not appear in the list and does not modify the list
print("The first position where 20 occured in the list is: ",newlist.index(20))
#The max() function determines the maximum number in a list
print("The maximum number in the list is:",max(newlist))
#The min() function determines the minimum number in a list
print("The minimum number in the list is:",min(newlist))
#The remove() function removes the first occurrence (lower index) of a given element from the list.Produces an
error if the element does not appear in the list and modify the list if item is removed
newlist.remove(60)
print("The newlist after removing element 60 is: \n",newlist)
#The append() function adds a new element to the end of the list.Modifies the list
newlist.append(222)
print("The newlist after adding element 222 is: \n",newlist)
#The insert() function inserts a new element before the element at a given index. Increases the length of the list
by one and modifies the list
newlist.insert (5,12)
print("The newlist after inserting an element 12 at an index before 5 is: \n",newlist)
#the pop() function return element at an specified index.If not mentioned returns last element
print("The last element of the list is: ",newlist.pop())
print("The fifth elemenet of the list is: ",newlist.pop(4))
#The len() function determines the length of the list.(Number of elemenets in the list)
print("The length of the newlist is: ",len(newlist))
#The sum() function displays the sum of all the elemenets of the list
print("The sum of all the elements in the newlist is: ",sum(newlist))
#The reverse() function physically reverses the elements in the list. The list is modified
newlist.reverse()
print("The reversed list is:\n",newlist)
#the sorted() function sorts the elemenets of the list in ascending order. The list is not modified
print("The sorted list without modifying the list is:\n",sorted(newlist))
print("The list is: ",newlist)
#the sort() function sorts the elements of the list in ascending order. The list is modified
newlist.sort()
print("The sorted list after modifying the list is:\n",newlist)
#The copy() function helps to create a new list similar to the original list
newlist2=newlist.copy()
#The extend() function helps to add a list to the existing list
templist=list([1,2,3])
newlist2.extend(templist)
print("The extended list is: \n",newlist2)
#The clear() function helps to clear the list by deleting all the elements
newlist2.clear()
print(newlist2)
print("The newlist is: ",newlist2)
OUTPUT:

The number of times 30 occured in the list is: 4


The first position where 20 occured in the list is: 1
The maximum number in the list is: 70
The minimum number in the list is: 10
The newlist after removing element 60 is:
[10, 20, 30, 40, 30, 30, 50, 70, 30]
The newlist after adding element 222 is:
[10, 20, 30, 40, 30, 30, 50, 70, 30, 222]
The newlist after inserting an element 12 at an index before 5 is:
[10, 20, 30, 40, 30, 12, 30, 50, 70, 30, 222]
The last element of the list is: 222
The fifth elemenet of the list is: 30
The length of the newlist is: 9
The sum of all the elements in the newlist is: 292
The reversed list is:
[30, 70, 50, 30, 12, 40, 30, 20, 10]
The sorted list without modifying the list is:
[10, 12, 20, 30, 30, 30, 40, 50, 70]
The list is: [30, 70, 50, 30, 12, 40, 30, 20, 10]
The sorted list after modifying the list is:
[10, 12, 20, 30, 30, 30, 40, 50, 70]
The extended list is:
[10, 12, 20, 30, 30, 30, 40, 50, 70, 1, 2, 3]
[]
The newlist is: []
PROGRAM 05
PROGRAM FOR USING FUNCTIONS FOR DICTIONARY
#Program for using functions for dictionary
#Program for accessing dictionary elements
emp_dict={'Name':'Jyotishman','Age':'35','Designation':'Manager'}
#Modifications in values of key named "Age"
emp_dict['Age']=40 #Modification in Age
print("The keyvalue pairs in the dictionary after modifying age are:\n",emp_dict.items())
#Adding a new keyvalue pair to the existing dictionary through three different approaches
emp_dict['Address']='Pune'
emp_dict.update({'Gender':'Male'})
emp_dict.setdefault('Qualification','MBA')
print("The keyvalue pairs in the dictionary after adding new keyvalue pairs are:\n",emp_dict.items())
#The get() function is used to fetching the value of the key("Designation")
print("The value of Designation key is: ",emp_dict.get('Designation'))
#The len() function is used to determine the length of the dictionary
print("The length of the dictionary is: ",len(emp_dict))
#The sorted() function is used to sort the keys in the alphabetic order
print("The sorted list is: \n",sorted(emp_dict))
#The pop() function is used to remove a particular key. Here Age key is removed
print("Using pop function to remove Age key: ",emp_dict.pop('Age'))
print("The keyvalue pairs in the dictionary after pop function are: \n",emp_dict.items())
#The copy() function is used to copy a dictionary in another dictionary
newemp_dict=emp_dict.copy()
print("The keyvalue pairs in the new dictionary is:\n",newemp_dict.items())
#The clear() function clears the contents of a dictionary and hence creates an empty dictionary
newemp_dict.clear()
print("The keyvalue pairs in the dictionary after using clear function are: \n",newemp_dict.items())
#The 'in' is used to determine the existence of key in dictionary
print("Does Name key exists in dictionary? ",'Name' in emp_dict)
print("Does City key exists in dictionary? ",'City' in emp_dict)
OUTPUT:

The keyvalue pairs in the dictionary after modifying age are:


dict_items([('Name', 'Jyotishman'), ('Age', 40), ('Designation', 'Manager')])
The keyvalue pairs in the dictionary after adding new keyvalue pairs are:
dict_items([('Name', 'Jyotishman'), ('Age', 40), ('Designation', 'Manager'), ('Address', 'Pune'), ('Gender', 'Male'),
('Qualification', 'MBA')])
The value of Designation key is: Manager
The length of the dictionary is: 6
The sorted list is:
['Address', 'Age', 'Designation', 'Gender', 'Name', 'Qualification']
Using pop function to remove Age key: 40
The keyvalue pairs in the dictionary after pop function are:
dict_items([('Name', 'Jyotishman'), ('Designation', 'Manager'), ('Address', 'Pune'), ('Gender', 'Male'),
('Qualification', 'MBA')])
The keyvalue pairs in the new dictionary is:
dict_items([('Name', 'Jyotishman'), ('Designation', 'Manager'), ('Address', 'Pune'), ('Gender', 'Male'),
('Qualification', 'MBA')])
The keyvalue pairs in the dictionary after using clear function are:
dict_items([])
Does Name key exists in dictionary? True
Does City key exists in dictionary? False
PROGRAM 06
PROGRAM TO SHOW USE OF random() AND seed() FUNCTIONS FROM RANDOM MODULE

#Program to show use of random() and seed() functions from random module
from random import random,seed
#The seed() sets the random number seed
seed(222)
print("The random number generated is: ",random())
#Using different seed value for displaying a random number
seed(500)
print("The random number generated using different seed value is: ",random())
OUTPUT:

The random number generated is: 0.7788164325646951


The random number generated using different seed value is: 0.7973375876367403
PROGRAM 07
PROGRAM TO USE MATHEMATICAL OPERATORS ON ARRAYS

#Program to use mathematical operators on arrays


import numpy
#Creating three integer arrays
myarray1=numpy.array([1,2,3],int)
myarray2=numpy.array([4,5,6],int)
myarray3=numpy.array([7,8,9],int)
#Performing addition and subtraction on all elements of an array
myarray4=myarray3+myarray2-myarray1
print("After addition and subtraction on all elements of the array is: \n",myarray4)
#Performing multiplication and division on all elements of the array
myarray5=(myarray3*myarray1)/myarray2
print("After multiplication division on all elements of the arrays is: \n",myarray5)
#Using modulus operator(%) on all elements of the array
myarray6=myarray2%myarray1
print("Using modulus operation on two arrays is: \n",myarray6)
#Using integer division (//) on all elements of the arrays
myarray7=myarray2//myarray1
print("Using integer division on teo arrays is: \n",myarray7)
OUTPUT:

After addition and subtraction on all elements of the array is:


[10 11 12]
After multiplication division on all elements of the arrays is:
[1.75 3.2 4.5 ]
Using modulus operation on two arrays is:
[0 1 0]
Using integer division on teo arrays is:
[4 2 2]
PROGRAM 08
PROGRAM TO PERFORM TRANSPOSING AND TO PRINT THE DIAGONAL AS WELL AS THE
LOWER DIAGONAL AND UPPER DIAGONAL ELEMENTS OF A 2D ARRAYS

import numpy as np
arr=np.array([[1,2,3,4],[5,6,7,8],[9,0,1,2],[3,4,5,6]])
print("ORIGINAL ARRAY IS: \n",arr)
print("TRANSPOSED ARRAY IS: \n",np.transpose(arr))
print("DIAGONAL WITH OFFSET 0 IS: \n",arr.diagonal(0))
print("DIAGONAL WITH OFFSET -1 (LOWER DIAGONAL) IS: \n",arr.diagonal(-1))
print("DIAGONAL WITH OFFSET 1 (UPPER DIAGONAL) IS: \n",arr.diagonal(1))
OUTPUT:

ORIGINAL ARRAY IS:


[[1 2 3 4]
[5 6 7 8]
[9 0 1 2]
[3 4 5 6]]
TRANSPOSED ARRAY IS:
[[1 5 9 3]
[2 6 0 4]
[3 7 1 5]
[4 8 2 6]]
DIAGONAL WITH OFFSET 0 IS:
[1 6 1 6]
DIAGONAL WITH OFFSET -1 (LOWER DIAGONAL) IS:
[5 0 5]
DIAGONAL WITH OFFSET 1 (UPPER DIAGONAL) IS:
[2 7 2]
PROGRAM 09
PROGRAM TO IMPLEMENT THE CONCEPT OF FUNCTIONS RELATED TO FIND AND
REPLACE OF A STRING

#Program to implement functions to find and replace of a string


newstring='Efficient and good people will bring a change'
#The len() function determines the length of the string
print("The length of the string is: ",len(newstring))
#The 'in' returns true if the string contains a substring
print("Is good present in the string: ",'good' in newstring)
#The startswith() function returns true if the string starts with the provided substring
print("Does the string starts with good: ",newstring.startswith("good"))
#The endswith() function returns true if the string ends with the provided substring
print("Does the string ends with change: ",newstring.endswith("change"))
#The replace() function replaces all the old substrings with new substring
print("The newstring is: ",newstring.replace('change','better change'))
#The count() function counts the non-overlapping occurrence of supplied substring in string
print("The number of times a occurred in the string is: ",newstring.count("a"))
#The find() function returns the index of first occurrence of supplied substring. Return -1 if not found
print("The first occurrence of go is in the string at index: ",newstring.find("go"))
#The rfind() function returns the index of last occurrence of supplied substring. Return -1 if not found
print("The last occurrence of ab is in the string at index: ",newstring.rfind("ab"))
#The index() function returns the index of first occurrence of supplied substring. Raise value error if not found
print("The first occurrence of ll is in the string at index: ",newstring.index("ll"))
#The rindex() function returns the index of last occurrence of supplied substring. Raise value error if not found
print("The last occurrence of an is in the string at index: ",newstring.rindex("an"))
OUTPUT:

The length of the string is: 45


Is good present in the string: True
Does the string starts with good: False
Does the string ends with change: True
The newstring is: Efficient and good people will bring a better change
The number of times a occurred in the string is: 3
The first occurrence of go is in the string at index: 14
The last occurrence of ab is in the string at index: -1
The first occurrence of ll is in the string at index: 28
The last occurrence of an is in the string at index: 41
PROGRAM 10
PROGRAM FOR DISPLAYING RECORDS FROM THE DATASET USING head() AND tail()
FUNCTION

#Program to determine and modify the path of current working directory


import os
print("The current working directory is: ",os.getcwd())
os.chdir("D:")
print("The current working directory is: ",os.getcwd())
#Importing pandas library
import pandas as pd
#Importing "csv" file and storing in dataframe
mydata=pd.read_csv("mtcars.csv")
#Displaying the information of the dataset using info() function
print("The information of the dataset is: ",mydata.info())
#Displaying the complete dataset using describe
print("The details of the dataset is:",mydata.describe)
#Displaying the descriptive statistical values of each column in the dataset using describe() function
print("The description of the dataset is:\n",mydata.describe())
#Program for displaying records from the dataset using head() and tail() functions
print("The first five records of the dataset is: \n",mydata.head())
#Displaying the first three records
print("The first three records of the dataset is: \n",mydata.head(3))
#Displaying the first three records of "mpg" and "hp"
print("The first three records of the selected columns from the dataset is:\n",mydata[['mpg','hp']].head(3))
#Displaying the last two records
print("The last two records of the dataset is: \n",mydata.tail(2))
#Displaying the last two records of "mpg" and "hp"
print("The last two records of the selected columns from the dataset is:\n",mydata[['mpg','hp']].tail(2))
#Determining all the values of gear column only
print("The values corresponding to gear column are:\n ",mydata['gear'].values)
OUTPUT:

The current working directory is: C:\Users\user


The current working directory is: D:\
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 32 entries, 0 to 31
Data columns (total 12 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 model 32 non-null object
1 mpg 32 non-null float64
2 cyl 32 non-null int64
3 disp 32 non-null float64
4 hp 32 non-null int64
5 drat 32 non-null float64
6 wt 32 non-null float64
7 qsec 32 non-null float64
8 vs 32 non-null int64
9 am 32 non-null int64
10 gear 32 non-null int64
11 carb 32 non-null int64
dtypes: float64(5), int64(6), object(1)
memory usage: 3.1+ KB
The information of the dataset is: None
The details of the dataset is: <bound method NDFrame.describe of model mpg cyl disp hp ...
qsec vs am gear carb
0 Mazda RX4 21.0 6 160.0 110 ... 16.46 0 1 4 4
1 Mazda RX4 Wag 21.0 6 160.0 110 ... 17.02 0 1 4 4
2 Datsun 710 22.8 4 108.0 93 ... 18.61 1 1 4 1
3 Hornet 4 Drive 21.4 6 258.0 110 ... 19.44 1 0 3 1
4 Hornet Sportabout 18.7 8 360.0 175 ... 17.02 0 0 3 2
5 Valiant 18.1 6 225.0 105 ... 20.22 1 0 3 1
6 Duster 360 14.3 8 360.0 245 ... 15.84 0 0 3 4
7 Merc 240D 24.4 4 146.7 62 ... 20.00 1 0 4 2
8 Merc 230 22.8 4 140.8 95 ... 22.90 1 0 4 2
9 Merc 280 19.2 6 167.6 123 ... 18.30 1 0 4 4
10 Merc 280C 17.8 6 167.6 123 ... 18.90 1 0 4 4
11 Merc 450SE 16.4 8 275.8 180 ... 17.40 0 0 3 3
12 Merc 450SL 17.3 8 275.8 180 ... 17.60 0 0 3 3
13 Merc 450SLC 15.2 8 275.8 180 ... 18.00 0 0 3 3
14 Cadillac Fleetwood 10.4 8 472.0 205 ... 17.98 0 0 3 4
15 Lincoln Continental 10.4 8 460.0 215 ... 17.82 0 0 3 4
16 Chrysler Imperial 14.7 8 440.0 230 ... 17.42 0 0 3 4
17 Fiat 128 32.4 4 78.7 66 ... 19.47 1 1 4 1
18 Honda Civic 30.4 4 75.7 52 ... 18.52 1 1 4 2
19 Toyota Corolla 33.9 4 71.1 65 ... 19.90 1 1 4 1
20 Toyota Corona 21.5 4 120.1 97 ... 20.01 1 0 3 1
21 Dodge Challenger 15.5 8 318.0 150 ... 16.87 0 0 3 2
22 AMC Javelin 15.2 8 304.0 150 ... 17.30 0 0 3 2
23 Camaro Z28 13.3 8 350.0 245 ... 15.41 0 0 3 4
24 Pontiac Firebird 19.2 8 400.0 175 ... 17.05 0 0 3 2
25 Fiat X1-9 27.3 4 79.0 66 ... 18.90 1 1 4 1
26 Porsche 914-2 26.0 4 120.3 91 ... 16.70 0 1 5 2
27 Lotus Europa 30.4 4 95.1 113 ... 16.90 1 1 5 2
28 Ford Pantera L 15.8 8 351.0 264 ... 14.50 0 1 5 4
29 Ferrari Dino 19.7 6 145.0 175 ... 15.50 0 1 5 6
30 Maserati Bora 15.0 8 301.0 335 ... 14.60 0 1 5 8
31 Volvo 142E 21.4 4 121.0 109 ... 18.60 1 1 4 2

[32 rows x 12 columns]>


The description of the dataset is:
mpg cyl disp ... am gear carb
count 32.000000 32.000000 32.000000 ... 32.000000 32.000000 32.0000
mean 20.090625 6.187500 230.721875 ... 0.406250 3.687500 2.8125
std 6.026948 1.785922 123.938694 ... 0.498991 0.737804 1.6152
min 10.400000 4.000000 71.100000 ... 0.000000 3.000000 1.0000
25% 15.425000 4.000000 120.825000 ... 0.000000 3.000000 2.0000
50% 19.200000 6.000000 196.300000 ... 0.000000 4.000000 2.0000
75% 22.800000 8.000000 326.000000 ... 1.000000 4.000000 4.0000
max 33.900000 8.000000 472.000000 ... 1.000000 5.000000 8.0000

[8 rows x 11 columns]
The first five records of the dataset is:
model mpg cyl disp hp ... qsec vs am gear carb
0 Mazda RX4 21.0 6 160.0 110 ... 16.46 0 1 4 4
1 Mazda RX4 Wag 21.0 6 160.0 110 ... 17.02 0 1 4 4
2 Datsun 710 22.8 4 108.0 93 ... 18.61 1 1 4 1
3 Hornet 4 Drive 21.4 6 258.0 110 ... 19.44 1 0 3 1
4 Hornet Sportabout 18.7 8 360.0 175 ... 17.02 0 0 3 2

[5 rows x 12 columns]
The first three records of the dataset is:
model mpg cyl disp hp drat wt qsec vs am gear carb
0 Mazda RX4 21.0 6 160.0 110 3.90 2.620 16.46 0 1 4 4
1 Mazda RX4 Wag 21.0 6 160.0 110 3.90 2.875 17.02 0 1 4 4
2 Datsun 710 22.8 4 108.0 93 3.85 2.320 18.61 1 1 4 1
The first three records of the selected columns from the dataset is:
mpg hp
0 21.0 110
1 21.0 110
2 22.8 93
The last two records of the dataset is:
model mpg cyl disp hp drat wt qsec vs am gear carb
30 Maserati Bora 15.0 8 301.0 335 3.54 3.57 14.6 0 1 5 8
31 Volvo 142E 21.4 4 121.0 109 4.11 2.78 18.6 1 1 4 2
The last two records of the selected columns from the dataset is:
mpg hp
30 15.0 335
31 21.4 109
The values corresponding to gear column are:
[4 4 4 3 3 3 3 4 4 4 4 3 3 3 3 3 3 4 4 4 3 3 3 3 3 4 5 5 5 5 5 4]
PROGRAM 11
PROGRAM THAT PLOT MARKS OBTAINED BY TWO STUDENTS IN SIX SUBJECTS USING
BARGRAPH

import numpy as np
import matplotlib.pyplot as plt
marks_Jia=(83,79,80,83,85,89)
marks_Gokul=(95,84,89,99,100,91)
index=np.array([1,2,3,4,5,6])
width=0.30
plt.bar(index,marks_Jia,width,label="Marks obtained by Jia")
plt.bar(index+width,marks_Gokul,width,label="Marks obtained by Gokul")
plt.ylabel=('Marks')
plt.title=("Comparing marks of Jia and Gokul")
plt.xticks(index+width/2,('subject1','subject2','subject3','subject4','subject5','subject6'))
plt.legend(loc='best')
plt.show()
OUTPUT:
PROGRAM 12
PROGRAM FOR CREATING A LINE CHART WITH SETTING LIMIT OF AXES

import matplotlib.pyplot as plt


plt.plot([2,3,7,11,13],[5,7,9,12,15],'go',[2,3,7,11,13],[5,7,9,12,15],'k')
#Adding labels to the x-axis
plt.xlabel('Numbers on X axis')
#Adding labels to the y-axis
plt.ylabel('Numbers on Y axis')
#Adding title to the chart
plt.title('Numbers on both axes')
#Setting the limit of both the axes
plt.axis([0,15,0,17])
#Displaying the chart
plt.show()
OUTPUT:
PROGRAM 13
PROGRAM TO PRINT THE MEASURES OF CENTRAL TENDENCY

#Import python libraries


import pandas as pd
import scipy.stats as s
score={'Physics':[62,47,55,74,31,55,85,63,42,32,71,55],'Maths':[89,87,67,55,47,72,76,79,44,92,99,47]}
#Print the dataframe
df=pd.DataFrame(score)
print(df)
#Arithmetic Mean value of the score columns in DataFrame
print("\n\n Arithmetic Mean values in the distribution")
print("Score 1",s.tmean(df["Physics"]).round(2))
print("Score 2",s.tmean(df["Maths"]).round(2))
#Harmonic Mean value of the score columns in DataFrame
print("\n\n Harmonic Mean values in the distribution")
print("Score 1",s.hmean(df["Physics"]).round(2))
print("Score 2",s.hmean(df["Maths"]).round(2))
#Geometric Mean value of the score columns in DataFrame
print("\n\n Geometic Mean values in the distribution")
print("Score 1",s.gmean(df["Physics"]).round(2))
print("Score 2",s.gmean(df["Maths"]).round(2))
#Median value of the score columns in DataFrame
print("\n\n Median values in the distribution")
print("Score 1",df["Physics"].median())
print("Score 2",df["Maths"].median())
#Mode value of the score columns in DataFrame
print("\n\n Mode values in the distribution")
print("Score 1",df["Physics"].mode())
print("Score 2",df["Maths"].mode())
OUTPUT:

Physics Maths
0 62 89
1 47 87
2 55 67
3 74 55
4 31 47
5 55 72
6 85 76
7 63 79
8 42 44
9 32 92
10 71 99
11 55 47

Arithmetic Mean values in the distribution


Score 1 56.0
Score 2 71.17

Harmonic Mean values in the distribution


Score 1 51.17
Score 2 66.01

Geometic Mean values in the distribution


Score 1 53.65
Score 2 68.63
Median values in the distribution
Score 1 55.0
Score 2 74.0

Mode values in the distribution


Score 1 0 55
Name: Physics, dtype: int64
Score 2 0 47
Name: Maths, dtype: int64
PROGRAM 14
PROGRAM TO CALCULATE THE t-TEST STATISTICS FOR 10 SAMPLES VALUES
#Import python libraries
import numpy as np
import statistics
import math
#Creating an array of numerical data
data=[480,520,410,556,505,610,470,464,530,485]
s=statistics.mean(data)
pm=450
t_crit=1.83
N=10
#Calculate standard deviation
sd=0
for e in data:
sd+=(float(e)-s)**2
sigma=math.sqrt(sd/(N-1))
den=sigma/np.sqrt(N)
t_stat=(s-pm)/den
print("ONE SAMPLE TWO TAILED t-TEST RESULTS")
print("-------------------------------\n")
print("Hypothesized population mean: ",round(pm,2))
print("Sample mean : ",s)
print("Sample size : ",N)
print("Standard deviation : ",round(sigma,2))
print("t-test results : ",round(t_stat,2))
print("t-critical : ",round(t_crit,2))
if (t_stat<t_crit):
print("\n Null hypothesis is accepted")
else:
print("\n Null hypothesis is rejected")
OUTPUT:

ONE SAMPLE TWO TAILED t-TEST RESULTS


-------------------------------

Hypothesized population mean: 450


Sample mean : 503
Sample size : 10
Standard deviation : 55.17
t-test results : 3.04
t-critical : 1.83

Null hypothesis is rejected


PROGRAM 15
PROGRAM TO DEMONSTRATE NORMAL DISTRIBUTION

import scipy.stats
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(1234)
sample=np.random.lognormal(mean=1.,sigma=.4,size=10000)
shape,loc,scale=scipy.stats.lognorm.fit(sample,floc=0)
num_bins=100
c="red"
counts,edges,patches=plt.hist(sample,bins=num_bins,color=c)
centers=0.5*(edges[:-1]+edges[1:])
cdf=scipy.stats.lognorm.cdf(edges,shape,loc=loc,scale=scale)
prob=np.diff(cdf)
plt.plot(centers,sample.size*prob,'k-',linewidth=2)
plt.title('Normal Distribution')
OUTPUT:
PROGRAM 16
PROGRAM TO IMPLEMENT LINEAR REGRESSION FOR A DATASET

# Import libraries
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.metrics import r2_score
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
import numpy as np
# Import dataset
dataset = pd.read_csv("C:/Users/user/Downloads/Salary Data.csv")
print(dataset)
# Split into training and testing dataset
x = dataset.iloc[:, [0]].values
y = dataset.iloc[:, [1]].values
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.33, random_state=0)
# Linear regression
regressor = LinearRegression()
regressor.fit(x_train, y_train)
y_pred = regressor.predict(x_test)
# Print variance score
print('\n\n Variance score: %.2f' % r2_score(y_test, y_pred))
# Plot Training Set
plt.scatter(x_train, y_train, color="red")
plt.plot(x_train, regressor.predict(x_train), color="blue")
plt.title("Salary vs Years of Experience (Training Set)")
plt.xlabel("Years of Experience")
plt.ylabel("Salary")
plt.show()
# Plot Test Set
plt.scatter(x_test, y_test, color="red") # Use test data
plt.plot(x_train, regressor.predict(x_train), color="blue") # Line remains from training data
plt.title("Salary vs Years of Experience (Test Set)")
plt.xlabel("Years of Experience")
plt.ylabel("Salary")
plt.show()
# Predict a new value
y_pred = regressor.predict(np.array([[13.5]])) # Reshapes to 2D array
print("\n\n Linear Regression \n Given new x value = 13.5")
print("Predicted Y value =", y_pred.round(2))
OUTPUT:

Experience Years Salary


0 1.1 39343
1 1.2 42774
2 1.3 46205
3 1.5 37731
4 2.0 43525
5 2.2 39891
6 2.5 48266
7 2.9 56642
8 3.0 60150
9 3.2 54445
10 3.2 64445
11 3.5 60000
12 3.7 57189
13 3.8 60200
14 3.9 63218
15 4.0 55794
16 4.0 56957
17 4.1 57081
18 4.3 59095
19 4.5 61111
20 4.7 64500
21 4.9 67938
22 5.1 66029
23 5.3 83088
24 5.5 82200
25 5.9 81363
26 6.0 93940
27 6.2 91000
28 6.5 90000
29 6.8 91738
30 7.1 98273
31 7.9 101302
32 8.2 113812
33 8.5 111620
34 8.7 109431
35 9.0 105582
36 9.5 116969
37 9.6 112635
38 10.3 122391
39 10.5 121872

Variance score: 0.91


PROGRAM 17
PROGRAM TO IMPLEMENT k-MEANS ALGORITHM

import matplotlib.pyplot as plt


from sklearn.cluster import KMeans # Corrected import
from sklearn.datasets import make_blobs
from sklearn.metrics import silhouette_score
from sklearn.preprocessing import StandardScaler
# Generate dataset
features, true_labels = make_blobs(n_samples=200, centers=3, cluster_std=2.75, random_state=42)
# Standardize features
scaler = StandardScaler()
scaled_features = scaler.fit_transform(features)
# Print first five samples
print("Features:\n", features[:5])
print("True Labels:\n", true_labels[:5])
print("Scaled Features:\n", scaled_features[:5])
# Apply K-Means clustering
kmeans = KMeans(n_clusters=3, init='k-means++', max_iter=300, random_state=42) # Corrected KMeans
usage
kmeans.fit(scaled_features)
# Print results
print("K-Means Inertia =", kmeans.inertia_)
print("Centers:", kmeans.cluster_centers_)
print("K-Means Labels:", kmeans.labels_[:5])
OUTPUT:

Features:
[[ 9.77075874 3.27621022]
[ -9.71349666 11.27451802]
[ -6.91330582 -9.34755911]
[-10.86185913 -10.75063497]
[ -8.50038027 -4.54370383]]
True Labels:
[1 0 2 2 2]
Scaled Features:
[[ 2.13082109 0.25604351]
[-1.52698523 1.41036744]
[-1.00130152 -1.56583175]
[-1.74256891 -1.76832509]
[-1.29924521 -0.87253446]]
K-Means Inertia = 74.57960106819854
Centers: [[ 1.19539276 0.13158148]
[-0.91941183 -1.18551732]
[-0.25813925 1.05589975]]
K-Means Labels: [0 2 1 1 1]

You might also like