20MCA36 PYTHON MANUAL
1. Write a Python program to perform linear search
n=int(input("Enter how many number "))
print("Enter ",n," numbers")
num=[]
for i in range(0,n):
num.append(int(input()))
sitem=int(input("Enter the search item"))
found=False
for i in range(0,n):
if(num[i]==sitem):
found=True
break
if(found==True):
print("Element found at ",i+1)
else:
print("Element not found")
OUTPUT
Enter how many number 4
Enter 4 numbers
4
2
6
8
Enter the search item 6
Element found at 3
2. Write a Python program to insert an element into a sorted list
def slist_insert(a,i):
b=[]
len1=len(a)
for n in range(0,len1):
if(int(a[n])<=i):
b.append(a[n])
else:
break
b.append(i)
len2=len(b)
for x in range(len2-1,len1):
b.append(a[x])
return b
a=[1,2,6]
print("array before insert",a)
i=int(input("input a number"))
print("Array after insert",slist_insert(a,i))
BIET DAVANAGERE 1
20MCA36 PYTHON MANUAL
OUTPUT
array before insert [1, 2, 6]
input a number 3
Array after insert [1, 2, 3, 6]
3. Write a python program using object oriented programming to demonstrate
encapsulation, overloading and inheritance
class Base:
x=10
def __init__(self):
self.a=10
self._b=20
def display(self):
print("a and b values are : ")
print(f"a={self.a} b={self._b}")
#overloaded method
def display(self,a,b):
print("a = ",a,"b = ",b)
class Derived(Base):
def __init__(self):
#inheritance-- printing base class variable 'a'
print("Accessing the Base class member",Base.x)
Base.__init__(self)
print("Calling protected member of base class : ",self._b)
obj1=Base()
obj2=Derived()
print("Calling overloaded method")
obj1.display(10,20)
#print(obj2.b) #Encapsulation --calling protected member of base class
OUTPUT
Accessing the Base class member 10
Calling protected member of base class : 20
Calling overloaded method
a = 10 b = 20
BIET DAVANAGERE 2
20MCA36 PYTHON MANUAL
4.Implement a python program to demonstrate
1) Importing Datasets 2) Cleaning the Data 3) Data frame manipulation using Numpy
import csv
import pandas as pd
#data imoprting
print("\nData importing")
df=pd.read_csv('flat.csv')
print(df)
#data cleaning
print("\nData Cleaning")
miss_val=["n/a","Na","--","N/A"]
df=pd.read_csv('flat.csv',na_values=miss_val)
df['ST_NUM'].fillna(125,inplace=True)
median=df['NUM_BEDROOMS'].median()
df['NUM_BEDROOMS'].fillna(median,inplace=True)
df['OWN_OCCUPIDE'].fillna('N',inplace=True)
df.loc[3,'OWN_OCCUPIDE']='Y'
print(df)
#data Manipulating
print("\nData Manipulating")
df.rename(columns={'ST_NUM':'Street Number','ST_NAME':'Street Name'},inplace=True)
df.insert(2,"ADD",[32,54,72,65,88,11,33,55,77])
print(df)
OUTPUT
Data importing
ST_NUM ST_ NAME NUM_BEDROOMS OWN_OCCUPIDE
0 105.0 MAHA 3.0 Y
1 197.0 GUJ 3.0 N
2 NaN MP NaN N
3 201.0 PU 1.0 12
4 203.0 KAR 3.0 Y
5 207.0 KER NaN Y
6 NaN TN 2.0 NaN
7 213.0 AP 3.0 Y
8 215.0 ASAM NaN Y
BIET DAVANAGERE 3
20MCA36 PYTHON MANUAL
Data Cleaning
ST_NUM ST_NAME NUM_BEDROOMS OWN_OCCUPIDE
0 105.0 MAHA 3.0 Y
1 197.0 GUJ 3.0 N
2 125.0 MP 3.0 N
3 201.0 PU 1.0 Y
4 203.0 KAR 3.0 Y
5 207.0 KER 3.0 Y
6 125.0 TN 2.0 N
7 213.0 AP 3.0 Y
8 215.0 ASAM 3.0 Y
Data Manipulating
Street Number Street Name ADD NUM_BEDROOMS OWN_OCCUPIDE
0 105.0 MAHA 32 3.0 Y
1 197.0 GUJ 54 3.0 N
2 125.0 MP 72 3.0 N
3 201.0 PU 65 1.0 Y
4 203.0 KAR 88 3.0 Y
5 207.0 KER 11 3.0 Y
6 125.0 TN 33 2.0 N
7 213.0 AP 55 3.0 Y
8 215.0 ASAM 77 3.0 Y
5.Implement a python program to demonstrate the following using NumPy
a) Array manipulation, Searching, Sorting and splitting
import numpy as np
a=np.array([[1,8],[2,7]])
b=np.array([[3,6],[4,5]])
c=np.concatenate((a,b),axis=None)
#Array manipulating
print("Concate with axis=0:\n",np.concatenate((a,b),axis=0))
print("Concate with axis=1\n:",np.concatenate((a,b),axis=1))
#Array searching
arr = np.array([1, 2, 3, 4, 5, 4, 4])
x = np.where(arr == 4)
print(x)
arr = np.array([6, 7, 8, 9])
x = np.searchsorted(arr, 5)
print(x)
BIET DAVANAGERE 4
20MCA36 PYTHON MANUAL
#Array sorting
arr = np.array([1, 7, 3, 4, 5, 2, 9])
print("Array before sorting ",arr)
print("Array after sorting ",np.sort(arr))
#Splitting array
newarr=np.array_split(c,3)
print(newarr)
OUTPUT
Concate with axis=0:
[[1 8]
[2 7]
[3 6]
[4 5]]
Concate with axis=1
: [[1 8 3 6]
[2 7 4 5]]
(array([3, 5, 6], dtype=int64),)
0
Array before sorting [1 8 2 7 3 6 4 5]
Array after sorting [1 2 3 4 5 6 7 8]
[array([1, 8, 2]), array([7, 3, 6]), array([4, 5])]
b) Broadcasting and Plotting NumPy arrays
import matplotlib.pyplot as plt
import numpy as np
#Array Broadcasting
a=np.array([5,7,3,1])
b=np.array([90,50,0,30])
c=a*b
print(c)
#Plotting an array
x=np.arange(0,3*np.pi,0.1)
y_sin=np.sin(x)
y_cos=np.cos(x)
plt.plot(x,y_sin)
plt.plot(x,y_cos)
plt.xlabel('x axis label')
plt.ylabel('y axis label')
BIET DAVANAGERE 5
20MCA36 PYTHON MANUAL
plt.title('Single and Cosine')
plt.legend(['Sine','Cosine'])
plt.show()
6. Implement a python program to demonstrate Data visualization with various Types
of Graphs using matplotlib
import matplotlib.pyplot as mplt
import numpy as np
#Line graph
x=[2,4,6,8]
y=[12,16,10,22]
mplt.plot(x,y)
mplt.title("My first graph")
mplt.xlabel("month")
mplt.ylabel("Subscription")
mplt.show()
#scater graph
mplt.plot([1,2,3,4],[5,6,7,8],"ro-",label="red dots")
mplt.plot([1,2,3,4],[3,4,9,10],"b*--",label="blue dots")
mplt.legend(loc="best")
mplt.show()
#bar graph
counts = [979,120,12]
fuelType = ('petrol','diesel','CNG')
index = np.arange(len(fuelType))
mplt.bar(index, counts,color=['orange','gray','green'])
plt.title('bar plot of the fuel types')
plt.xlabel('fueltype')
plt.ylabel('frequency')
plt.xticks(index,fuelType,rotation=0)
BIET DAVANAGERE 6
20MCA36 PYTHON MANUAL
plt.show()
OUTPUT
BIET DAVANAGERE 7
20MCA36 PYTHON MANUAL
7.Write a Python program that creates a mxn integer arrayand Prints its attributes
using Numpy
import numpy as np
a = np.array([[12,4,5],[23,45,66],[45,34,23]])
print("Printing Array")
print()
print(a)
print()
print("Printing numpy array Attributes")
print("1>. Array Shape is: ", a.shape)
print("2>. Array dimensions are ", a.ndim)
print("3>. Datatype of array is ", a.dtype)
print("4>. Length of each element of array in bytes is ", a.itemsize)
print("5>. Number of elements in array are ", a.size)
OUTPUT
Printing Array
[[12 4 5]
[23 45 66]
[45 34 23]]
Printing numpy array Attributes
1>. Array Shape is: (3, 3)
2>. Array dimensions are 2
3>. Datatype of array is int32
4>. Length of each element of array in bytes is 4
5>. Number of elements in array are 9
8.Write a Python program to demonstrate the generation of linear regression models.
import numpy as np
import matplotlib.pyplot as plt
def estimate_coef(x, y):
# number of observations/points
n = np.size(x)
# mean of x and y vector
m_x = np.mean(x)
m_y = np.mean(y)
# calculating cross-deviation and deviation about x
SS_xy = np.sum(y*x) - n*m_y*m_x
SS_xx = np.sum(x*x) - n*m_x*m_x
# calculating regression coefficients
b_1 = SS_xy / SS_xx
b_0 = m_y - b_1*m_x
return (b_0, b_1)
def plot_regression_line(x, y, b):
# plotting the actual points as scatter plot
plt.scatter(x, y, color = "m", marker = "o", s = 30)
BIET DAVANAGERE 8
20MCA36 PYTHON MANUAL
# predicted response vector
y_pred = b[0] + b[1]*x
# plotting the regression line
plt.plot(x, y_pred, color = "g")
# putting labels
plt.xlabel('x')
plt.ylabel('y')
# function to show plot
plt.show()
def main():
# observations / data
x = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
y = np.array([1, 3, 2, 5, 7, 8, 8, 9, 10, 12])
# estimating coefficients
b = estimate_coef(x, y)
print("Estimated coefficients:\nb_0 = {} \ \nb_1 = {}".format(b[0], b[1]))
# plotting regression line
plot_regression_line(x, y, b)
if __name__ == "__main__":
main()
output
BIET DAVANAGERE 9
20MCA36 PYTHON MANUAL
9.Write a Python program to demonstrate the generation of logistic regression models
using Python.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
dataset = pd.read_csv('User_Data.csv')
x = dataset.iloc[:, [2, 3]].values
y = dataset.iloc[:, 4].values
from sklearn.model_selection import train_test_split
xtrain, xtest, ytrain, ytest = train_test_split(x, y, test_size = 0.25, random_state = 0)
from sklearn.preprocessing import StandardScaler
sc_x = StandardScaler()
xtrain = sc_x.fit_transform(xtrain)
xtest = sc_x.transform(xtest)
print (xtrain[0:10, :])
from sklearn.linear_model import LogisticRegression
classifier = LogisticRegression(random_state = 0)
classifier.fit(xtrain, ytrain)
y_pred = classifier.predict(xtest)
from sklearn.metrics import confusion_matrix
cm = confusion_matrix(ytest, y_pred)
print ("Confusion Matrix : \n", cm)
from sklearn.metrics import accuracy_score
print ("Accuracy : ", accuracy_score(ytest, y_pred))
from matplotlib.colors import ListedColormap
X_set, y_set = xtest, ytest
X1, X2 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 1,
stop = X_set[:, 0].max() + 1, step = 0.01),
np.arange(start = X_set[:, 1].min() - 1,
stop = X_set[:, 1].max() + 1, step = 0.01))
plt.contourf(X1, X2, classifier.predict(
np.array([X1.ravel(), X2.ravel()]).T).reshape(
X1.shape), alpha = 0.75, cmap = ListedColormap(('red', 'green')))
plt.xlim(X1.min(), X1.max())
plt.ylim(X2.min(), X2.max())
for i, j in enumerate(np.unique(y_set)):
plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1],color = ListedColormap(('red',
'green'))(i), label = j)
plt.title('Classifier (Test set)')
plt.xlabel('Age')
plt.ylabel('Estimated Salary')
plt.legend()
BIET DAVANAGERE 10
20MCA36 PYTHON MANUAL
plt.show()
OUTPUT
BIET DAVANAGERE 11
20MCA36 PYTHON MANUAL
10.Write a Python program to demonstrate Timeseries analysis with Pandas.
import pandas as pd
df = pd.read_csv("aapl.csv",parse_dates=["Date"], index_col="Date")
df.head()
Open High Low Close Volume
Date
2017-07-07 142.90 144.75 142.90 144.18 19201712
2017-07-06 143.02 143.50 142.41 142.73 24128782
2017-07-05 143.69 144.79 142.72 144.09 21569557
2017-07-03 144.88 145.30 143.10 143.50 14277848
2017-06-30 144.45 144.96 143.78 144.02 23024107
df.index
DatetimeIndex(['2017-07-07', '2017-07-06', '2017-07-05', '2017-07-03',
'2017-06-30', '2017-06-29', '2017-06-28', '2017-06-27',
'2017-06-26', '2017-06-23',
...
'2016-07-22', '2016-07-21', '2016-07-20', '2016-07-19',
'2016-07-18', '2016-07-15', '2016-07-14', '2016-07-13',
'2016-07-12', '2016-07-11'],
dtype='datetime64[ns]', name='Date', length=251, freq=None)
# (1) Partial Date Index: Select Specific Months Data
df.loc['2017-06-30']
Open High Low Close Volume
Date
2017-06-30 144.45 144.96 143.78 144.02 23024107
df.loc["2017-01"]
Open High Low Close Volume
Date
2017-01-31 121.15 121.39 120.62 121.35 49200993
2017-01-30 120.93 121.63 120.66 121.63 30377503
2017-01-27 122.14 122.35 121.60 121.95 20562944
2017-01-26 121.67 122.44 121.60 121.94 26337576
2017-01-25 120.42 122.10 120.28 121.88 32586673
2017-01-24 119.55 120.10 119.50 119.97 23211038
2017-01-23 120.00 120.81 119.77 120.08 22050218
2017-01-20 120.45 120.45 119.73 120.00 32597892
2017-01-19 119.40 120.09 119.37 119.78 25597291
2017-01-18 120.00 120.50 119.71 119.99 23712961
2017-01-17 118.34 120.24 118.22 120.00 34439843
2017-01-13 119.11 119.62 118.81 119.04 26111948
2017-01-12 118.90 119.30 118.21 119.25 27086220
2017-01-11 118.74 119.93 118.60 119.75 27588593
2017-01-10 118.77 119.38 118.30 119.11 24462051
BIET DAVANAGERE 12
20MCA36 PYTHON MANUAL
df.loc['2017-06'].head()
Open High Low Close Volume
Date
2017-06-30 144.45 144.96 143.78 144.02 23024107
2017-06-29 144.71 145.13 142.28 143.68 31499368
2017-06-28 144.49 146.11 143.16 145.83 22082432
2017-06-27 145.01 146.16 143.62 143.73 24761891
2017-06-26 147.17 148.28 145.38 145.82 25692361
#Average price of aapl's stock in June, 2017
df.loc['2017-06'].Close.mean()
147.8313636363636
df.loc['2017'].head(2)
Open High Low Close Volume
Date
2017-07-07 142.90 144.75 142.90 144.18 19201712
2017-07-06 143.02 143.50 142.41 142.73 24128782
df['2017-01-08':'2017-01-03']
df.loc['2017-01']
df['Close'].resample('M').mean().head()
df.loc['2016-07']
%matplotlib inline
df['Close'].plot()
df['Close'].resample('M').mean().plot(kind='bar')
BIET DAVANAGERE 13
20MCA36 PYTHON MANUAL
11.Write a Python program to demonstrate Data Visualization using Seaborn.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
cars_data = pd.read_csv('Toyota.csv', index_col=0, na_values=["??","????"])
cars_data.dropna(axis=0, inplace= True)
sns.set(style="darkgrid")
sns.regplot(x=cars_data['Age'],y= cars_data['Price'])
BIET DAVANAGERE 14
20MCA36 PYTHON MANUAL
# scatter plot of Price and age without the regeression fitline
sns.regplot(x=cars_data['Age'],y= cars_data['Price'],marker='*' ,fit_reg=False)
# scatter plot of price vs age by FuelType
sns.lmplot(x='Age',y='Price', data=cars_data, fit_reg=False, hue="FuelType", legend=True, palette="Set1")
BIET DAVANAGERE 15
20MCA36 PYTHON MANUAL
#distribution of the variable 'Age'
sns.histplot(cars_data['Age'])
sns.histplot(cars_data['Age'],kde=False, bins = 8)
BIET DAVANAGERE 16