You are on page 1of 35

1 of 35 10/23

PYTHON PROGRAMMING LAB

Program 1: Python Programs on Lists & Dictionaries

LISTS PROGRAM:
l = [8, 'hi', 'bye']
print(l)
l.append('wow')
print(l)
l.insert(2,"hai")
print(l)
print(l.count('bye'))
l.pop(1)
print(l)
a = l.index(8)
print(a)
l.reverse()
print(l)
l.remove('bye')
print(l)

OUTPUT:

AUCOE
[8, 'hi', 'bye']
[8, 'hi', 'bye', 'wow']
[8, 'hi', 'hai', 'bye', 'wow']
1
[8, 'hai', 'bye', 'wow']
0
['wow', 'bye', 'hai', 8]
['wow', 'hai', 8]

10/28 1 of 35
2 of 35 10/23

DICTIONARIES PROGRAM:
d = {1: "a", 2: "b", 3: "c"}
print(d)
d2=d.copy()
print(d2)
d[4] = "d"
print(d)
d.pop(3)
print(d)
d.update({2: "x"})
print(d)
print(d.keys())
print(d.values())
print(d.get(1))
del d[4]
print(d)
d2.clear()

AUCOE
print(d2)

OUTPUT:
{1: 'a', 2: 'b', 3: 'c'}
{1: 'a', 2: 'b', 3: 'c'}
{1: 'a', 2: 'b', 3: 'c', 4: 'd'}
{1: 'a', 2: 'b', 4: 'd'}
{1: 'a', 2: 'x', 4: 'd'}
dict_keys([1, 2, 4])
dict_values(['a', 'x', 'd'])
a
{1: 'a', 2: 'x'}
{}
10/28 2 of 35
3 of 35 10/23

Program 2: Python Programs on Searching and Sorting

SEARCHING PROGRAMS

LINEAR SEARCH PROGRAM:

def linear_Search(list1, n, key):


for i in range(0, n):
if (list1[i] == key):
return i
return -1
list1 = [1, 3, 5, 4, 7, 9]
key = 7
n = len(list1)
res = linear_Search(list1, n, key)
if (res == -1):
print("Element not found")
else:
print("Element found at index:",res)

AUCOE
OUTPUT:
Element found at index: 4

10/28 3 of 35
4 of 35 10/23

BINARY SEARCH PROGRAM:

def binary_search(list1, n):


low = 0
high = len(list1) - 1
mid = 0
while low <= high:
# for get integer result
mid = (high + low) // 2
if list1[mid] < n:
low = mid + 1
elif list1[mid] > n:
high = mid - 1
else:
return mid
return -1
list1 = [12, 24, 32, 39, 45, 50, 54]
n = 45
result = binary_search(list1, n)

AUCOE
if result != -1:
print("Element is present at index", str(result))
else:
print("Element is not present in list1")

OUTPUT:
Element is present at index 4

10/28 4 of 35
5 of 35 10/23

SORTING PROGRAMS

BUBBLE SORT PROGRAM:

def bubble_sort(list1):
for i in range(0, len(list1) - 1):
for j in range(len(list1) - 1):
if (list1[j] > list1[j + 1]):
temp = list1[j]
list1[j] = list1[j + 1]
list1[j + 1] = temp
return list1
list1 = [5, 3, 8, 6, 7, 2]
print("The unsorted list is: ", list1)
print("The sorted list is: ", bubble_sort(list1))

OUTPUT:
The unsorted list is: [5, 3, 8, 6, 7, 2]
The sorted list is: [2, 3, 5, 6, 7, 8]

AUCOE
10/28 5 of 35
6 of 35 10/23

SELECTION SORT PROGRAM:

def selection_sort(array):
length = len(array)
for i in range(length - 1):
minIndex = i
for j in range(i + 1, length):
if array[j] < array[minIndex]:
minIndex = j
array[i], array[minIndex] = array[minIndex], array[i]
return array
array = [21, 6, 9, 33, 3]
print("The sorted array is: ", selection_sort(array))

OUTPUT:
The sorted array is: [3, 6, 9, 21, 33]

AUCOE
10/28 6 of 35
7 of 35 10/23

INSERTION SORT PROGRAM:

def insertion_sort(list1):
for i in range(1, len(list1)):
value = list1[i]
j=i-1
while j >= 0 and value < list1[j]:
list1[j + 1] = list1[j]
j -= 1
list1[j + 1] = value
return list1
list1 = [10, 5, 13, 8, 2]
print("The unsorted list is:", list1)
print("The sorted list1 is:", insertion_sort(list1))

OUTPUT:

The unsorted list is: [10, 5, 13, 8, 2]


The sorted list1 is: [2, 5, 8, 10, 13]

AUCOE
10/28 7 of 35
8 of 35 10/23

QUICK SORT PROGRAM:

def quicksort(arr, lo, hi):


if lo < hi:
p = partition(arr, lo, hi)
quicksort(arr, lo, p - 1)
quicksort(arr, p + 1, hi)
def partition(arr, lo, hi):
pivot = arr[hi]
i = lo - 1
for j in range(lo, hi):
if arr[j] <= pivot:
i += 1
arr[i], arr[j] = arr[j], arr[i]
arr[i + 1], arr[hi] = arr[hi], arr[i + 1]
return i + 1
arr = [10, 7, 8, 9, 1, 5]
n = len(arr)
quicksort(arr, 0, n - 1)
print("Sorted array:", arr)

AUCOE
OUTPUT:

Sorted array: [1, 5, 7, 8, 9, 10]

10/28 8 of 35
9 of 35 10/23

MERGE SORT PROGRAM:

def merge_sort(list1, left_index, right_index):


if left_index >= right_index:
return
middle = (left_index + right_index) // 2
merge_sort(list1, left_index, middle)
merge_sort(list1, middle + 1, right_index)
merge(list1, left_index, right_index, middle)

def merge(list1, left_index, right_index, middle):


left_sublist = list1[left_index:middle + 1]
right_sublist = list1[middle + 1:right_index + 1]
left_sublist_index = 0
right_sublist_index = 0
sorted_index = left_index
while left_sublist_index < len(left_sublist) and right_sublist_index <
len(right_sublist):

if left_sublist[left_sublist_index] <= right_sublist[right_sublist_index]:


list1[sorted_index] = left_sublist[left_sublist_index]

AUCOE
left_sublist_index = left_sublist_index + 1
else:
list1[sorted_index] = right_sublist[right_sublist_index]
right_sublist_index = right_sublist_index + 1
sorted_index = sorted_index + 1

while left_sublist_index < len(left_sublist):


list1[sorted_index] = left_sublist[left_sublist_index]
left_sublist_index = left_sublist_index + 1
sorted_index = sorted_index + 1

10/28 9 of 35
10 of 35 10/23

while right_sublist_index < len(right_sublist):


list1[sorted_index] = right_sublist[right_sublist_index]
right_sublist_index = right_sublist_index + 1
sorted_index = sorted_index + 1
list1 = [44, 65, 2, 3, 58, 14, 57, 23, 10, 1, 7, 74, 48]
merge_sort(list1, 0, len(list1) - 1)

print(list1)

OUTPUT:

[1, 2, 3, 7, 10, 14, 23, 44, 48, 57, 58, 65, 74]

AUCOE
10/28 10 of 35
11 of 35 10/23

HEAP SORT PROGRAM:


def heapify(arr, n, i):
largest = i # Initialize largest as root
l = 2 * i + 1 # left = 2*i + 1
r = 2 * i + 2 # right = 2*i + 2
if l < n and arr[i] < arr[l]:
largest = l
if r < n and arr[largest] < arr[r]:
largest = r
if largest != i:
(arr[i], arr[largest]) = (arr[largest], arr[i]) # swap
heapify(arr, n, largest)
def heapSort(arr):
n = len(arr)
for i in range(n // 2 - 1, -1, -1):
heapify(arr, n, i)
for i in range(n - 1, 0, -1):
(arr[i], arr[0]) = (arr[0], arr[i]) # swap
heapify(arr, i, 0)
arr = [12, 11, 13, 5, 6, 7, ]
heapSort(arr)
n = len(arr)

AUCOE
print('Sorted array is')
for i in range(n):
print(arr[i])

OUTPUT:
Sorted array is 5
6
7
11
12
13
10/28 11 of 35
12 of 35 10/23

Program 3: Python Programs on Text Handling

def count_words(text):
words = text.split()
return len(words)
def count_characters(text):
return len(text)
def reverse_text(text):
return text[::-1]
def capitalize_text(text):
return text.upper()
def find_substring(text, substring):
if substring in text:
return "The substring "+substring+" is found in the text."
else:
return f"The substring '{substring}' is not found in the text."
input_text = input("Enter some text: ")
print(f"Number of words: {count_words(input_text)}")
print(f"Number of characters: {count_characters(input_text)}")
print(f"Reversed text: {reverse_text(input_text)}")
print(f"Capitalized text: {capitalize_text(input_text)}")
substring = input("Enter a substring to search for: ")

AUCOE
print(find_substring(input_text, substring))

OUTPUT:

Enter some text: THIS IS ROSHAN


Number of words: 3
Number of characters: 15
Reversed text: NAHSOR SI SIHT
Capitalized text: THIS IS ROSHAN
Enter a substring to search for: ROSHAN
The substring ROSHAN is found in the text.

10/28 12 of 35
13 of 35 10/23

Program 4: Python Programs on File Handling

# Writing to a file in "w" mode


with open("output.txt", "w") as file:
file.write("Hello, this is a line written to the file.")
# Appending to the same file in "a" mode
with open("output.txt", "a") as file:
file.write("\nThis line is appended to the file.")
# Reading the entire file using .read()
with open("output.txt", "r") as file:
content = file.read()
print("File content:\n", content)
# Getting the current position using .tell()
with open("output.txt", "r") as file:
position = file.tell()
print("Current position:", position)
# Seeking to a specific position using .seek()
with open("output.txt", "r") as file:
file.seek(10) # Move the pointer to position 10
seekread = file.read()
print("File data from position 10:", seekread)
file.close()

AUCOE
OUTPUT:

File content:
Hello, this is a line written to the file.
This line is appended to the file.
Current position: 0
File data from position 10: s is a line written to the file.
This line is appended to the file.

10/28 13 of 35
14 of 35 10/23

Program 5: Python Programs for calculating Mean, Mode, Median,


Variance, Standard Deviation

import statistics
numbers = input("Enter a list of numbers (space-separated): ").split()
numbers = list(map(float, numbers))
mean = sum(numbers) / len(numbers)
mode = statistics.mode(numbers)
median = statistics.median(numbers)
variance = statistics.variance(numbers)
std_deviation = statistics.stdev(numbers)
print("\nMean:", mean)
print("\nMode:", mode)
print("\nMedian:", median)
print("\nVariance:", variance)
print("\nStandard Deviation:", std_deviation)

OUTPUT:

Enter a list of numbers: 1 2 3 4


Mean:2.5

AUCOE
Mode:1.0
Median:2.5
Variance:1.66666
Standard deviation:1.2909944487358056

10/28 14 of 35
15 of 35 10/23

Program 6: Python Programs for Karl Pearson Coefficient of


Correlation, Rank Correlation

n = int(input("Enter the number of data points: "))


x = [float(input(f"Enter x value {i + 1}: ")) for i in range(n)]
y = [float(input(f"Enter y value {i + 1}: ")) for i in range(n)]
m_x, m_y = sum(x) / n, sum(y) / n
p = sum((x[i] - m_x) * (y[i] - m_y) for i in range(n)) / (sum((x[i] - m_x)**2 for i in
range(n)) ** 0.5 * sum((y[i] - m_y)**2 for i in range(n)) ** 0.5)
r_x,r_y = [sorted(x).index(v) + 1 for v in x], [sorted(y).index(v) + 1 for v in y]
r = 1 - 6 * sum((r_x[i] - r_y[i]) ** 2 for i in range(n)) / (n * (n**2 - 1))
print("Pearson Correlation:", p)
print("Rank Correlation:", r)

OUTPUT:

Enter the number of data points: 2


Enter x value 1: 1
Enter x value 2: 2
Enter y value 1: 5
Enter y value 2: 6
Pearson Correlation: 0.9999999999999998

AUCOE
Rank Correlation: 1.0

10/28 15 of 35
16 of 35 10/23

Program 7: Python Programs on NumPy Arrays, Linear algebra


with NumPy

import numpy as np
# Get the dimensions of the system
n = int(input("Enter the number of variables: "))
# Get the coefficient matrix
A = np.zeros((n, n))
print("Enter the coefficient matrix:")
for i in range(n):
A[i] = list(map(float, input().split()))
# Get the constant vector
b = np.zeros(n)
print("Enter the constant vector:")
b = list(map(float, input().split()))
# Solve the linear equation Ax = b
x = np.linalg.solve(A, b)
print("Solution x:", x)

OUTPUT:

Enter the number of variables:2

AUCOE
Enter the coefficient matrix:
10
01
Enter the constant vector: 1 0
Solution X : [1,0]

10/28 16 of 35
17 of 35 10/23

Program 8: Python Programs for creation and manipulation of


Data Frames using Pandas Library

import pandas as pd
data = {'Name': ['Alex', 'Bob'], 'Age': [25, 30], 'Country': ['USA', 'UK'], 'Salary':
[6000, 7500]}
df = pd.DataFrame(data)
print("\nInitial DataFrame:\n",df)
print("\nName column:\n",df['Name'])
print("\nAge column:\n",df['Age'])
df['Experience'] = [3, 5]
df.loc[0, 'Age'] = 31
df.at[1, 'Country'] = 'Australia'
df.drop('Salary', axis=1, inplace=True)
filtered_data = df[df['Age'] > 25]
sorted_data = df.sort_values(by='Age')
print("\nModified DataFrame: \n",df)
print("\nFiltered DataFrame: \n",filtered_data)
print("\nSorted DataFrame: \n",sorted_data)

OUTPUT:

AUCOE
Initial DataFrame:
Name Age Country Salary
0 Alex 25 USA 6000
1 Bob 30 UK 7500
Name column:
0 Alex
1 Bob
Name: Name, dtype: object

10/28 17 of 35
18 of 35 10/23

Age column:
0 25
1 30
Name: Age, dtype: int64

Modified DataFrame:
Name Age Country Experience
0 Alex 31 USA 3
1 Bob 30 Australia 5

Filtered DataFrame:
Name Age Country Experience
0 Alex 31 USA 3
1 Bob 30 Australia 5

Sorted DataFrame:
Name Age Country Experience
1 Bob 30 Australia 5
0 Alex 31 USA 3

AUCOE
10/28 18 of 35
19 of 35 10/23

Program 9: Write a Python program for the following

A) SIMPLE LINE PLOTS

import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 10, 100)
y = np.sin(x)
plt.figure()
plt.plot(x, y)
plt.title("Simple Line Plot")
plt.show()

OUTPUT:

AUCOE
10/28 19 of 35
20 of 35 10/23

B) ADJUSTING THE PLOT

import numpy as np
import matplotlib.pyplot as plt
plt.figure()
plt.plot(x, y, color='red', linestyle='dashed', linewidth=2, label='sin(x)')
plt.xlim(0, 10)
plt.ylim(-1, 1)
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Adjusted Plot')
plt.legend()
plt.show()

OUTPUT:

AUCOE
10/28 20 of 35
21 of 35 10/23

C) SIMPLE SCATTER PLOT

import numpy as np
import matplotlib.pyplot as plt
plt.figure()
x_scatter = np.random.rand(50)
y_scatter = np.random.rand(50)
plt.scatter(x_scatter, y_scatter, marker='o', color='blue')
plt.title('Simple Scatter Plot')
plt.show()

OUTPUT:

AUCOE
10/28 21 of 35
22 of 35 10/23

D) HISTOGRAM

import numpy as np
import matplotlib.pyplot as pltplt.figure()
data = np.random.randn(1000)
plt.hist(data, bins=20, alpha=0.7, color='green')
plt.title('Histogram')
plt.show()

OUTPUT:

AUCOE
10/28 22 of 35
23 of 35 10/23

E) CUSTOMIZING PLOT LEGENDS


import numpy as np
import matplotlib.pyplot as plt
import matplotlib.pyplot as plt
x, y1, y2 = [1, 2, 3, 4, 5], [1, 4, 1, 3, 1], [1, 2, 1, 2, 1]
plt.plot(x, y1, label='Line 1')
plt.plot(x, y2, label='Line 2')
plt.legend(title='Legend', loc='upper left', fontsize='small')
plt.title('Customized Legend')
plt.xlabel('X-axis'), plt.ylabel('Y-axis')
plt.show()

OUTPUT:

AUCOE
10/28 23 of 35
24 of 35 10/23

F) BOXPLOT
import numpy as np
import matplotlib.pyplot as pltplt.figure()
data_box = np.random.randn(100, 5)
plt.boxplot(data_box)
plt.title('Boxplot')
plt.show()

OUTPUT:

AUCOE
10/28 24 of 35
25 of 35 10/23

G) MULTIPLE LEGENDS
import numpy as np
import matplotlib.pyplot as plt
plt.figure()
plt.plot(x, y, label='sin(x)')
plt.plot(x, np.cos(x), label='cos(x)')
plt.legend()
plt.legend(loc='upper right')
plt.title('Multiple Legends')

OUTPUT:

AUCOE
10/28 25 of 35
26 of 35 10/23

H) CUSTOMIZING COLOR BARS


import numpy as np
import matplotlib.pyplot as plt
plt.figure()
x_mesh, y_mesh = np.meshgrid(np.linspace(-5, 5, 50), np.linspace(-5, 5, 50))
z_mesh = np.sin(np.sqrt(x_mesh ** 2 + y_mesh ** 2))
plt.pcolormesh(x_mesh, y_mesh, z_mesh, cmap='viridis')
plt.colorbar()
plt.title('Customized Color Bar')
plt.show()

OUTPUT:

AUCOE
10/28 26 of 35
27 of 35 10/23

I) MULTIPLE SUBPLOTS

import numpy as np
import matplotlib.pyplot as plt
plt.figure(figsize=(10, 8))
plt.subplot(2, 2, 1)
plt.plot(x, y)
plt.title('Subplot 1')
plt.subplot(2, 2, 2)
plt.scatter(x_scatter, y_scatter)
plt.title('Subplot 2')
plt.show()

OUTPUT:

AUCOE
10/28 27 of 35
28 of 35 10/23

J) TEXT AND ANNOTATION

import numpy as np
import matplotlib.pyplot as plt
plt.figure()
plt.plot(x, y)
plt.text(2, 0.5, 'Annotation', fontsize=12, color='red')
plt.title('Text and Annotation')
plt.show()

OUTPUT:

AUCOE
10/28 28 of 35
29 of 35 10/23

K) CUSTOMIZING TICKS

import numpy as np
import matplotlib.pyplot as plt
plt.figure()
plt.plot(x, y)
plt.xticks(np.arange(0, 11, step=2))
plt.yticks(np.arange(-1, 1.5, step=0.5))
plt.title('Customized Ticks')
plt.show()

OUTPUT:

AUCOE
10/28 29 of 35
30 of 35 10/23

Program 10: Python Programs for Data Preprocessing: Handling


missing values, handling categorical data, bringing features to same
scale, selecting meaningful features.

import pandas as pd
from sklearn.preprocessing import LabelEncoder, StandardScaler
from sklearn.feature_selection import SelectKBest, f_classif
data = {
'Name': ['Alice', 'Bob', 'Charlie', 'David', 'Eve'],
'Age': [20, 21, None, 19, 22],
'Gender': ['Female', 'Male', 'Male', 'Male', 'Female'],
'Score': [85, 92, 78, None, 95],
'Grade': ['A', 'A', 'B', 'C', 'A']
}
df = pd.DataFrame(data)
print("Pre Processed data:\n", df)
df['Age'].fillna(df['Age'].mean(), inplace=True)
df['Score'].fillna(df['Score'].median(), inplace=True)
label_encoder = LabelEncoder()
df['Gender'] = label_encoder.fit_transform(df['Gender'])

AUCOE
df['Grade'] = label_encoder.fit_transform(df['Grade'])
scaler = StandardScaler()
df[['Age', 'Score']] = scaler.fit_transform(df[['Age', 'Score']])
X = df[['Age', 'Gender', 'Score']]
y = df['Grade']
X_new = SelectKBest(f_classif, k=1).fit_transform(X, y)
print("Processed Data:\n", df)
print("Selected Features:\n", X_new)

10/28 30 of 35
31 of 35 10/23

OUTPUT:

Pre Processed data:


Name Age Gender Score Grade
0 Alice 20.0 Female 85.0 A
1 Bob 21.0 Male 92.0 A
2 Charlie NaN Male 78.0 B
3 David 19.0 Male NaN C
4 Eve 22.0 Female 95.0 A

Processed Data:
Name Age Gender Score Grade
0 Alice -0.5 0 -0.457956 0
1 Bob 0.5 1 0.729338 0
2 Charlie 0.0 1 -1.645250 1
3 David -1.5 1 0.135691 2
4 Eve 1.5 0 1.238178 0

Selected Features:
[[-0.45795613]

AUCOE
[ 0.72933755]
[-1.64524981]
[ 0.13569071]
[ 1.2381777 ]]

10/28 31 of 35
32 of 35 10/23

Program 11: Python Program for Compressing data via


dimensionality reduction: PCA

import numpy as np
from sklearn.decomposition import PCA
# Principal component analysis (PCA)
X = np.random.rand(5, 3)
pca = PCA(n_components=2)
# Fit the model with X and apply the dimensionality reduction on X.
X_pca = pca.fit_transform(X)
print("Original data shape:", X.shape)
print("Set: \n", X)
print("Explained variance ratio:", pca.explained_variance_ratio_)
print("Compressed data shape:", X_pca.shape)
print("Set: \n", X_pca)

OUTPUT:
Original data shape: (5, 3)
Set:
[[0.92759375 0.56840535 0.91598183]
[0.08679916 0.23164186 0.03988349]
[0.59271507 0.49916463 0.55093995]

AUCOE
[0.80187812 0.26577533 0.94654278]
[0.2211008 0.10208069 0.34687052]]
Explained variance ratio: [0.91797906 0.08162075]
Compressed data shape: (5, 2)
Set:
[[-0.57586947 -0.10746775]
[ 0.68383843 -0.07764663]
[-0.0786081 -0.16040789]
[-0.43946613 0.19197858]
[ 0.41010526 0.15354369]]

10/28 32 of 35
33 of 35 10/23

Program 12: Python Programs for Data Clustering

import numpy as np
from sklearn.cluster import KMeans
num_clusters = int(input("Enter the number of clusters: "))
num_points = int(input("Enter the number of data points: "))
print("Enter the data points (format: x y):")
X = []
for i in range(num_points):
x, y = map(float, input().split())
X.append([x, y])
X = np.array(X)
kmeans = KMeans(n_clusters=num_clusters)
kmeans.fit(X)
print("Cluster Labels:", kmeans.labels_)
print("Cluster Centers:", kmeans.cluster_centers_)

OUTPUT:

Enter the number of clusters: 2


Enter the number of data points: 4

AUCOE
Enter the data points (format: x y):
11
1.5 1.5
44
4.5 4.5
Cluster Labels: [0 0 1 1]
Cluster Centers: [[1.25 1.25]
[4.25 4.25]]

10/28 33 of 35
34 of 35 10/23

Program 13: Python Programs for Classification

from sklearn.datasets import load_iris


from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score
iris = load_iris()
X_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target,
test_size=0.144, random_state=1500)
knn = KNeighborsClassifier(n_neighbors=3)
knn.fit(X_train, y_train)
y_pred = knn.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)

OUTPUT:

Accuracy: 0.9090909090909091

AUCOE
10/28 34 of 35
35 of 35 10/23

Program 14: Python Programs for Model Evaluation: K-fold cross-


validation

from sklearn.datasets import load_iris


from sklearn.model_selection import cross_val_score
from sklearn.neighbors import KNeighborsClassifier
iris = load_iris()
knn = KNeighborsClassifier(n_neighbors=9)
scores = cross_val_score(knn, iris.data, iris.target, cv=4)
print("Cross-validation scores:", scores)
avg_score = scores.mean()
print("Average score:", avg_score)

OUTPUT:

Cross-validation scores: [0.97368421 0.94736842 0.91891892 0.97297297]


Average score: 0.9532361308677098

AUCOE
10/28 35 of 35

You might also like