#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())
[Link](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())
[Link](x)
[Link]()
key = int(input("Enter element to be inserted: "))
[Link](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()
[Link]()
[Link]()
[Link]()
y = [Link](10,20)
print("After adding :",y)
z = [Link]("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\\[Link]')
df
[Link]()
[Link]()
#print no of rows and cols in csv file
print(len([Link][0]))
print(len([Link][1]))
#printing missing values
print([Link]().mean())
print("Total missing Values:",[Link]().[Link]())
#dealing the missing values
[Link](0, inplace=True)
#after replacing missing value
print([Link]().[Link]())
#printing duplicated rows
print(df[[Link]()])
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 = [Link]([[1,2,3],[4,5,6]])
arr2 = [Link]([[7,8,9],[10,11,12]])
print("Concatenation of array =",[Link]([arr1,arr2]))
print("Concatenation of array =",[Link]([arr1,arr2],axis =1))
print("Vertical stack =",[Link]((arr1,arr2)))
print("Horizontal stack =",[Link]((arr1,arr2)))
# seaching ,Sorting
arr3 = [Link]([1,2,3,4,5,4])
x = [Link](arr3 == 4)
print(x)
arr4 = [Link]([6,7,8])
x = [Link](arr4,8)
print(x)
arr5 = [Link]([4,3,5,2,1])
print("Sorted Array :",[Link](arr5))
# Splitting
arr6 = [Link]([1,2,3,4,5,6,7,8])
print([Link](arr6,2))
arr7 = [Link]([[1,2,3,4],[5,6,7,8]])
print([Link](arr7,2))
print([Link](arr7,2))
#(b)
# Broadcasting
arr8 = [Link]([1, 2, 3])
arr9 = [Link]([4, 5])
print("Broadcasting:")
print("arr8 * arr9 = ", [Link](arr8, (3, 1)) * arr9)
arr10 = [Link]([[1, 2, 3], [4, 5, 6]])
arr11 = [Link]([[1, 2], [3, 4], [5, 6]])
print("arr10 + arr11 =", [Link](arr11, (2,3)) + arr10)
# Plotting
import numpy as np
import [Link] as plt
x = [Link](0,3*[Link],0.1)
y_sin = [Link](x)
y_cos = [Link](x)
[Link](x,y_sin)
[Link](x,y_cos)
[Link]("x axis label")
[Link]("y axis label")
[Link]("sine and cosine")
[Link](['sine','cosine'])
[Link]()
OUTPUT:
#6. Implement a python program to demonstrate Data visualization with various Types of
Graphs using Numpy
import numpy as np
import [Link] as plt
# Line plot
# Generating sample data
x = [Link]([1,2,3,4,5])
y = x*2
[Link](figsize=(10, 6))
[Link](x,y)
[Link]('Line Plot')
[Link]('x-axis')
[Link]('y-axis')
[Link](True)
[Link]()
# 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]
[Link](figsize=(10, 6))
[Link](x1,y1)
[Link](x2,y2)
[Link]('Scatter Plot')
[Link]('x-axis')
[Link]('y-axis')
[Link](x2,y2)
[Link](True)
[Link]()
# Histogram
data = [Link](0, 1, 1000)
[Link](figsize=(10, 6))
[Link](data, bins=30, color='green', edgecolor='black')
[Link]('Histogram')
[Link]('Value')
[Link]('Frequency')
[Link](True)
[Link]()
# Bar plot
categories = ['A', 'B', 'C', 'D', 'E']
values = [7, 13, 5, 17, 10]
[Link](figsize=(10, 6))
[Link](categories, values, color='blue')
[Link]('Bar Plot')
[Link]('Category')
[Link]('Value')
[Link](True)
[Link]()
# Pie chart
sizes = [15, 30, 45, 10]
labels = ['A', 'B', 'C', 'D']
[Link](figsize=(10, 6))
[Link](sizes, labels=labels,autopct='%1.1f%%') #The '%1.1f%%' format means percentages will
be displayed with 1 decimal place.
[Link]('Pie Chart')
[Link]('equal')
[Link]()
OUTPUT:
#7. Write a Python program that creates a mxn integer array and Prints its attributes using
matplotlib
import numpy as np
arr= [Link]([[10,20,30],[40,50,60]],int)
print(arr)
print("Dimension attribute=",[Link])
print("Shape attribute=",[Link])
print("Size attribute=",[Link])
print("Itemsize attribute=",[Link])
print("Dtype attribute=",[Link])
print("Nbytes attribute=",[Link])
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 [Link] 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 = [Link]([1, 2, 3, 4, 5]).reshape(-1, 1)
y = [Link]([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
[Link](x, y, color='red', label='Data')
[Link](x, [Link](x),label='Linear Regression')
[Link]('x')
[Link]('y')
[Link]('Linear Regression Model')
[Link]()
[Link]()
OUTPUT:
Coefficients: [2.]
Intercept: 1.0
# 9. Write a Python program to demonstrate the generation of logistic regression models.
import numpy as np
import [Link] 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 = [Link]([1, 2, 3, 4, 5]).reshape(-1, 1)
y = [Link]([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
[Link](x, y, color='red', label='Data')
[Link](x, model.predict_proba(x)[:, 1], label='Logistic Regression')
[Link]('x')
[Link]('y')
[Link]('Logistic Regression Model')
[Link]()
[Link]()
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 [Link] as plt
# Generating sample data - time series of temperature readings with random values
[Link](0)
dates = pd.date_range(start='2024-01-01', periods=10)
data = {'Temperature': [Link](0, 30, size=10)}
# Create a DataFrame from the sample data
df = [Link](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 = [Link]('M').mean()
# Plot temperature readings
[Link](figsize=(10, 5))
[Link]('Temperature Readings Over Time')
[Link]('Date')
[Link]('Temperature (°C)')
[Link](True)
[Link]()
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 = [Link](tips)
[Link](x="tip",y='total_bill',data=data)
[Link](x="tip",y='total_bill',data=data,hue='day')
[Link](data['tip'],kde=True)
[Link](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']