Python Programs Andhra University Cse 3-1
Python Programs Andhra University Cse 3-1
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
SEARCHING PROGRAMS
AUCOE
OUTPUT:
Element found at index: 4
10/28 3 of 35
4 of 35 10/23
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
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
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
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:
AUCOE
10/28 7 of 35
8 of 35 10/23
AUCOE
OUTPUT:
10/28 8 of 35
9 of 35 10/23
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
10/28 9 of 35
10 of 35 10/23
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
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
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:
10/28 12 of 35
13 of 35 10/23
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
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:
AUCOE
Mode:1.0
Median:2.5
Variance:1.66666
Standard deviation:1.2909944487358056
10/28 14 of 35
15 of 35 10/23
OUTPUT:
AUCOE
Rank Correlation: 1.0
10/28 15 of 35
16 of 35 10/23
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:
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
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
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
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
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
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
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
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
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:
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
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
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:
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
OUTPUT:
Accuracy: 0.9090909090909091
AUCOE
10/28 34 of 35
35 of 35 10/23
OUTPUT:
AUCOE
10/28 35 of 35