#1. Write a Python program to perform linear search.
a=[]
n= int(input("Enter how many elements: "))
print("Enter array elements: ")
for i in range(n):
x = int(input())
a.append(x)
key = int(input("Enter an element to be searched: "))
f = 0
for i in a:
if i == key:
f=1
break
if f == 1:
print("Key found")
else:
print("Key not found")
OUTPUT:
Enter how many elements: 5
Enter array elements:
3
8
9
1
4
Enter an element to be searched: 8
Key found
#2. Write a Python program to insert an element into a sorted list
import bisect as b
lst = []
n = int(input("Enter n:"))
print("Enter list elements in sorted order:")
for i in range(n):
x = int(input())
lst.append(x)
lst.sort()
key = int(input("Enter element to be inserted: "))
b.insort(lst,key)
print("Contents of list after insertion:")
for i in lst:
print(i,end=" ")
OUTPUT:
Enter list elements in sorted order:
1
3
4
5
6
Enter element to be inserted: 2
Contents of list after insertion:
1 2 3 4 5 6
#3. Write a python program using object oriented programming to demonstrate
encapsulation, overloading and inheritance
class A:
def __init__(self):
self.a = 0
self.b = 0
def getdata(self):
self.a = int(input("Enter a :"))
self.b = int(input("Enter b :"))
def putdata(self):
print("a=",self.a,"b=",self.b)
class B(A):
def __init__(self):
self.c = 0
def sum(self):
self.c = self.a + self.b
print(self.c)
def add(self,m,n):
s = m + n
return s
x = B()
x.getdata()
x.putdata()
x.sum()
y = x.add(10,20)
print("After adding :",y)
z = x.add("Hello" , "World")
print("After Concatentation:",z)
OUTPUT:
Enter a :23
Enter b :56
a= 23 b= 56
79
After adding : 30
After Concatentation: HelloWorld
#4. Implement a python program to demonstrate 1) Importing Datasets 2) Cleaning the Data
3) Data frame manipulation using Numpy
import pandas as pd
#importing Datasets
df=pd.read_csv('C:\\Users\\bikas\\Downloads\\Toyota.csv')
df
df.head()
df.tail()
#print no of rows and cols in csv file
print(len(df.axes[0]))
print(len(df.axes[1]))
#printing missing values
print(df.isnull().mean())
print("Total missing Values:",df.isnull().values.sum())
#dealing the missing values
df.fillna(0, inplace=True)
#after replacing missing value
print(df.isnull().values.sum())
#printing duplicated rows
print(df[df.duplicated()])
OUTPUT:
1436
11
Unnamed: 0 0.000000
Price 0.000000
Age 0.069638
KM 0.000000
FuelType 0.069638
HP 0.000000
MetColor 0.104457
Automatic 0.000000
CC 0.000000
Doors 0.000000
Weight 0.000000
dtype: float64
Total missing Values: 350
0
Empty DataFrame
Columns: [Unnamed: 0, Price, Age, KM, FuelType, HP, MetColor, Automatic, CC, Doors, Weight]
Index: [ ]
#5. Implement a python program to demonstrate the following using NumPy a) Array
manipulation, Searching, Sorting and splitting. b) broadcasting and Plotting NumPy arrays
# (a)
import numpy as np
arr1 = np.array([[1,2,3],[4,5,6]])
arr2 = np.array([[7,8,9],[10,11,12]])
print("Concatenation of array =",np.concatenate([arr1,arr2]))
print("Concatenation of array =",np.concatenate([arr1,arr2],axis =1))
print("Vertical stack =",np.vstack((arr1,arr2)))
print("Horizontal stack =",np.hstack((arr1,arr2)))
# seaching ,Sorting
arr3 = np.array([1,2,3,4,5,4])
x = np.where(arr3 == 4)
print(x)
arr4 = np.array([6,7,8])
x = np.searchsorted(arr4,8)
print(x)
arr5 = np.array([4,3,5,2,1])
print("Sorted Array :",np.sort(arr5))
# Splitting
arr6 = np.array([1,2,3,4,5,6,7,8])
print(np.split(arr6,2))
arr7 = np.array([[1,2,3,4],[5,6,7,8]])
print(np.hsplit(arr7,2))
print(np.vsplit(arr7,2))
#(b)
# Broadcasting
arr8 = np.array([1, 2, 3])
arr9 = np.array([4, 5])
print("Broadcasting:")
print("arr8 * arr9 = ", np.reshape(arr8, (3, 1)) * arr9)
arr10 = np.array([[1, 2, 3], [4, 5, 6]])
arr11 = np.array([[1, 2], [3, 4], [5, 6]])
print("arr10 + arr11 =", np.reshape(arr11, (2,3)) + arr10)
# Plotting
import numpy as np
import matplotlib.pyplot as plt
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")
plt.title("sine and cosine")
plt.legend(['sine','cosine'])
plt.show()
OUTPUT:
#6. Implement a python program to demonstrate Data visualization with various Types of
Graphs using Numpy
import numpy as np
import matplotlib.pyplot as plt
# Line plot
# Generating sample data
x = np.array([1,2,3,4,5])
y = x*2
plt.figure(figsize=(10, 6))
plt.plot(x,y)
plt.title('Line Plot')
plt.xlabel('x-axis')
plt.ylabel('y-axis')
plt.grid(True)
plt.show()
# Scatter plot
x1=[1,2,3,4,5]
y1=[2,5,2,6,8]
x2=[1,2,3,4,5]
y2=[4,5,8,9,19]
plt.figure(figsize=(10, 6))
plt.scatter(x1,y1)
plt.scatter(x2,y2)
plt.title('Scatter Plot')
plt.xlabel('x-axis')
plt.ylabel('y-axis')
plt.plot(x2,y2)
plt.grid(True)
plt.show()
# Histogram
data = np.random.normal(0, 1, 1000)
plt.figure(figsize=(10, 6))
plt.hist(data, bins=30, color='green', edgecolor='black')
plt.title('Histogram')
plt.xlabel('Value')
plt.ylabel('Frequency')
plt.grid(True)
plt.show()
# Bar plot
categories = ['A', 'B', 'C', 'D', 'E']
values = [7, 13, 5, 17, 10]
plt.figure(figsize=(10, 6))
plt.bar(categories, values, color='blue')
plt.title('Bar Plot')
plt.xlabel('Category')
plt.ylabel('Value')
plt.grid(True)
plt.show()
# Pie chart
sizes = [15, 30, 45, 10]
labels = ['A', 'B', 'C', 'D']
plt.figure(figsize=(10, 6))
plt.pie(sizes, labels=labels,autopct='%1.1f%%') #The '%1.1f%%' format means percentages will
be displayed with 1 decimal place.
plt.title('Pie Chart')
plt.axis('equal')
plt.show()
OUTPUT:
#7. Write a Python program that creates a mxn integer array and Prints its attributes using
matplotlib
import numpy as np
arr= np.array([[10,20,30],[40,50,60]],int)
print(arr)
print("Dimension attribute=",arr.ndim)
print("Shape attribute=",arr.shape)
print("Size attribute=",arr.size)
print("Itemsize attribute=",arr.itemsize)
print("Dtype attribute=",arr.dtype)
print("Nbytes attribute=",arr.nbytes)
OUTPUT:
[[10 20 30]
[40 50 60]]
Dimension attribute= 2
Shape attribute= (2, 3)
Size attribute= 6
Itemsize attribute= 4
Dtype attribute= int32
Nbytes attribute= 24
# 8. Write a Python program to demonstrate the generation of linear regression models.
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
# Define array x and reshape it into a column vector and array y with corresponding target
values
x = np.array([1, 2, 3, 4, 5]).reshape(-1, 1)
y = np.array([3, 5, 7, 9, 11])
# Creating and training the linear regression model
model = LinearRegression().fit(x, y)
# Print the model coefficients and intercept
print('Coefficients:', model.coef_)
print('Intercept:', model.intercept_)
# Plotting the data and the linear regression line
plt.scatter(x, y, color='red', label='Data')
plt.plot(x, model.predict(x),label='Linear Regression')
plt.xlabel('x')
plt.ylabel('y')
plt.title('Linear Regression Model')
plt.legend()
plt.show()
OUTPUT:
Coefficients: [2.]
Intercept: 1.0
# 9. Write a Python program to demonstrate the generation of logistic regression models.
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LogisticRegression
# Define array x and reshape it into a column vector and array y with corresponding target
values
x = np.array([1, 2, 3, 4, 5]).reshape(-1, 1)
y = np.array([0, 0, 1, 1, 1]) # Binary classification, so using 0 and 1 as target labels
# Creating and training the logistic regression model
model = LogisticRegression().fit(x, y)
# Print the model coefficients and intercept
print('Coefficients:', model.coef_)
print('Intercept:', model.intercept_)
# Plotting the data and the logistic regression line
plt.scatter(x, y, color='red', label='Data')
plt.plot(x, model.predict_proba(x)[:, 1], label='Logistic Regression')
plt.xlabel('x')
plt.ylabel('y')
plt.title('Logistic Regression Model')
plt.legend()
plt.show()
OUTPUT:
Coefficients: [[1.04696432]]
Intercept: [-2.53376385]
#10. Write a Python program to demonstrate Time series analysis with Pandas.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# Generating sample data - time series of temperature readings with random values
np.random.seed(0)
dates = pd.date_range(start='2024-01-01', periods=10)
data = {'Temperature': np.random.randint(0, 30, size=10)}
# Create a DataFrame from the sample data
df = pd.DataFrame(data, index=dates)
df
# Calculate rolling mean (moving average) for temperature readings
rolling_mean = df['Temperature'].rolling(window=2).mean()
#Calculate percentage change in temperature readings
percentage_change = df['Temperature'].pct_change() * 100
# Resample data to monthly frequency
monthly_resampled = df.resample('M').mean()
# Plot temperature readings
df.plot(figsize=(10, 5))
plt.title('Temperature Readings Over Time')
plt.xlabel('Date')
plt.ylabel('Temperature (°C)')
plt.grid(True)
plt.show()
OUTPUT:
Temperature
2024-01-01 12
2024-01-02 15
2024-01-03 21
2024-01-04 0
2024-01-05 3
2024-01-06 27
2024-01-07 3
2024-01-08 7
2024-01-09 9
2024-01-10 19
#11. Write a Python program to demonstrate Data Visualization using Seaborn
import seaborn as sns
import pandas as pd
sns.get_dataset_names()
tips = sns.load_dataset('tips')
data = pd.DataFrame(tips)
sns.scatterplot(x="tip",y='total_bill',data=data)
sns.scatterplot(x="tip",y='total_bill',data=data,hue='day')
sns.histplot(data['tip'],kde=True)
sns.boxplot(x="day",y='tip',data=data,hue='sex')
OUTPUT:
['anagrams',
'anscombe',
'attention',
'brain_networks',
'car_crashes',
'diamonds',
'dots',
'dowjones',
'exercise',
'flights',
'fmri',
'geyser',
'glue',
'healthexp',
'iris',
'mpg',
'penguins',
'planets',
'seaice',
'taxis',
'tips',
'titanic']