0% found this document useful (0 votes)
2 views14 pages

Python Programming Laboratory

The document contains a series of Python programming exercises covering string manipulation, arithmetic operations, numerical methods, statistics, linear regression, and machine learning algorithms using Scikit-learn. Each section includes code examples and outputs demonstrating the implementation of various concepts such as finding roots of equations, computing central tendency measures, and applying classification and regression techniques. The document serves as a comprehensive guide for practical programming tasks in Python.

Uploaded by

wilado5043
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views14 pages

Python Programming Laboratory

The document contains a series of Python programming exercises covering string manipulation, arithmetic operations, numerical methods, statistics, linear regression, and machine learning algorithms using Scikit-learn. Each section includes code examples and outputs demonstrating the implementation of various concepts such as finding roots of equations, computing central tendency measures, and applying classification and regression techniques. The document serves as a comprehensive guide for practical programming tasks in Python.

Uploaded by

wilado5043
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

PYTHON PROGRAMMING LABORATORY

1. Write a program to create, concatenate and print a string and accessing sub-string from
given string
Program:
# Creating a string
string1 = "Hello"
string2 = "World"

# Concatenating two strings


concatenated_string = string1 + " " + string2

# Printing the concatenated string


print("Concatenated String:", concatenated_string)

# Accessing a substring (Extracting "World" from concatenated string)


substring = concatenated_string[6:11]
print("Extracted Substring:", substring)
Output:
Concatenated String: Hello World
Extracted Substring: World

2. Write a program to perform basic arithmetic operations using function evaluation, root of
equations and nonlinear solution methods.
#2.
# Function for basic arithmetic operations
def arithmetic_operations(a, b):
print("Addition:", a + b)
print("Subtraction:", a - b)
print("Multiplication:", a * b)
print("Division:", a / b if b != 0 else "Undefined (Division by
zero)")

# Function whose root we need to find (x^2 - 4 = 0)


def equation(x):
return x**2 - 4

# Derivative of the equation f(x) = x^2 - 4


def derivative(x):
return 2 * x
# Newton-Raphson method to find root
def newton_raphson(x0, tol=1e-6):
x = x0
while abs(equation(x)) > tol:
x = x - equation(x) / derivative(x)
return x

# Demonstration
a, b = 10, 5
print("Basic Arithmetic Operations:")
arithmetic_operations(a, b)

# Finding root using Newton-Raphson


root = newton_raphson(1.0) # Initial guess = 1.0
print("\nRoot of x^2 - 4 = 0 is:", root)

Basic Arithmetic Operations:


Addition: 15
Subtraction: 5
Multiplication: 50
Division: 2.0

Root of x^2 - 4 = 0 is: 2.0000000929222947

3. Write a program to find the solutions of various numerical methods.


#3
# Function whose root we need to find (Example: x^3 - x - 2 = 0)
def equation(x):
return x**3 - x - 2

# Derivative of the equation for Newton-Raphson Method


def derivative(x):
return 3*x**2 - 1

# 1. Bisection Method
def bisection_method(a, b, tol=1e-6):
if equation(a) * equation(b) >= 0:
print("Invalid range. The function must have opposite signs at
a and b.")
return None
while abs(b - a) > tol:
mid = (a + b) / 2
if equation(mid) == 0:
return mid
elif equation(mid) * equation(a) < 0:
b = mid
else:
a = mid
return (a + b) / 2 # Approximate root

# 2. Newton-Raphson Method
def newton_raphson(x0, tol=1e-6):
x = x0
while abs(equation(x)) > tol:
x = x - equation(x) / derivative(x)
return x

# 3. Secant Method
def secant_method(x0, x1, tol=1e-6, max_iter=100):
for _ in range(max_iter):
if abs(equation(x1)) < tol:
return x1
x_temp = x1 - (equation(x1) * (x1 - x0)) / (equation(x1) -
equation(x0))
x0, x1 = x1, x_temp
return x1 # Approximate root

# Solving using different methods


root_bisection = bisection_method(1, 2)
root_newton = newton_raphson(1.5)
root_secant = secant_method(1, 2)

# Printing the results


if root_bisection is not None:
print("Root using Bisection Method:", root_bisection)
print("Root using Newton-Raphson Method:", root_newton)
print("Root using Secant Method:", root_secant)

Root using Bisection Method: 1.5213799476623535


Root using Newton-Raphson Method: 1.5213798059647863
Root using Secant Method: 1.5213797079848717
6. Write a python program to define a module to find Fibonacci numbers and import the
module to another program

# [Link] - Module to find Fibonacci numbers

def fibonacci(n):
a, b = 0, 1
for _ in range(n):
print(a, end=" ")
a, b = b, a + b

# This section is no longer an import, but instead directly calls the


fibonacci function.
# This avoids the need for a separate module import.
n = int(input("Enter the number of Fibonacci terms: "))
fibonacci(n) # Call the function directly
Enter the number of Fibonacci terms: 7
0112358
9. Write a python program to compute Central Tendency Measures and Measure of
Dispersion: Variance, Standard Deviation

Python Program:

import statistics # Importing statistics module

# Function to compute central tendency and dispersion measures


def compute_statistics(data):
print("Data:", data)

# Central Tendency Measures


mean = [Link](data)
median = [Link](data)
mode = [Link](data)

# Measures of Dispersion
variance = [Link](data)
std_dev = [Link](data)

# Printing results
print("\nCentral Tendency Measures:")
print("Mean:", mean)
print("Median:", median)
print("Mode:", mode)

print("\nMeasures of Dispersion:")
print("Variance:", variance)
print("Standard Deviation:", std_dev)

# Taking user input


numbers = list(map(float, input("Enter numbers separated by space:
").split()))

# Calling function
compute_statistics(numbers)

Example Output:
Enter numbers separated by space: 10 20 30 40 50

Data: [10.0, 20.0, 30.0, 40.0, 50.0]


Central Tendency Measures:

Mean: 30.0

Median: 30.0

Mode: 10.0

Measures of Dispersion:

Variance: 250.0

Standard Deviation: 15.811388300841896

10. Write a Python program to implement Simple Linear Regression

Python Program:
import numpy as np
import [Link] as plt
from sklearn.linear_model import LinearRegression

# Sample data (independent variable X and dependent variable Y)


X = [Link]([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]).reshape(-1, 1)
Y = [Link]([2, 4, 5, 4, 5, 6, 8, 9, 10, 12])

# Creating and training the model


model = LinearRegression()
[Link](X, Y)

# Predicting values
Y_pred = [Link](X)

# Printing slope and intercept


print("Slope (Coefficient):", model.coef_[0])
print("Intercept:", model.intercept_)

# Plotting the regression line


[Link](X, Y, color='blue', label="Actual Data")
[Link](X, Y_pred, color='red', linewidth=2, label="Regression Line")
[Link]("X - Independent Variable")
[Link]("Y - Dependent Variable")
[Link]()
[Link]("Simple Linear Regression")
[Link]()
Output:
Slope (Coefficient): 1.0
Intercept: 1.0
11. Use of Scikit-learn tools for classification, regression, clustering and dimensionality
reduction.
import numpy as np
import [Link] as plt
from sklearn.linear_model import LogisticRegression, LinearRegression
from [Link] import KMeans
from [Link] import PCA
from [Link] import make_classification, make_regression,
make_blobs

# ----- 1. Classification using Logistic Regression -----


X_class, y_class = make_classification(n_samples=100, n_features=2,
n_informative=2, n_redundant=0, random_state=42)
# n_informative is changed to 2 so that 2**n_informative (2**2 = 4) is
greater than or equal to n_classes * n_clusters_per_class (2 * 2 = 4)
clf = LogisticRegression() # This line was previously part of the
comment above. Moved it out to properly initialize clf
[Link](X_class, y_class)
print("Classification Score:", [Link](X_class, y_class))

# ----- 2. Regression using Linear Regression -----


X_reg, y_reg = make_regression(n_samples=100, n_features=1, noise=10,
random_state=42)
reg = LinearRegression()
[Link](X_reg, y_reg)
print("Regression Coefficient:", reg.coef_[0])
print("Regression Intercept:", reg.intercept_)

# ----- 3. Clustering using K-Means -----


X_cluster, _ = make_blobs(n_samples=100, centers=3, random_state=42)
kmeans = KMeans(n_clusters=3, random_state=42, n_init=10)
[Link](X_cluster)
labels = kmeans.labels_

# ----- 4. Dimensionality Reduction using PCA -----


pca = PCA(n_components=2)
X_pca = pca.fit_transform(X_cluster)
print("Explained Variance Ratio:", pca.explained_variance_ratio_)

# Plotting Clustering Results


[Link](X_cluster[:, 0], X_cluster[:, 1], c=labels, cmap='viridis',
edgecolors='k')
[Link](kmeans.cluster_centers_[:, 0], kmeans.cluster_centers_[:,
1], s=200, color='red', marker='X', label="Centroids")
[Link]("K-Means Clustering")
[Link]()
[Link]()

Classification Score: 0.99


Regression Coefficient: 44.43716999225497
Regression Intercept: 1.1651153205269726
Explained Variance Ratio: [0.74467002 0.25532998]
12. Use of SciKit-learn tools to implement Naïve bayes, Random Forest Algorithm.

import numpy as np
import [Link] as plt
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
from [Link] import RandomForestClassifier
from [Link] import make_classification
from [Link] import accuracy_score

# Generating a synthetic dataset


X, y = make_classification(n_samples=200, n_features=5,
random_state=42)

# Splitting the dataset into training and testing sets


X_train, X_test, y_train, y_test = train_test_split(X, y,
test_size=0.2, random_state=42)

# ----- 1. Naïve Bayes Classifier -----


nb_model = GaussianNB() # Creating model
nb_model.fit(X_train, y_train) # Training model
y_pred_nb = nb_model.predict(X_test) # Making predictions

# ----- 2. Random Forest Classifier -----


rf_model = RandomForestClassifier(n_estimators=100, random_state=42) #
Creating model
rf_model.fit(X_train, y_train) # Training model
y_pred_rf = rf_model.predict(X_test) # Making predictions

# Calculating accuracy
accuracy_nb = accuracy_score(y_test, y_pred_nb)
accuracy_rf = accuracy_score(y_test, y_pred_rf)
# Printing results
print("Naïve Bayes Accuracy:", accuracy_nb)
print("Random Forest Accuracy:", accuracy_rf)

# Plot feature importance for Random Forest


feature_importance = rf_model.feature_importances_
[Link](range(len(feature_importance)), feature_importance,
color='blue')
[Link]("Feature Index")
[Link]("Importance Score")
[Link]("Feature Importance in Random Forest")
[Link]()

Naïve Bayes Accuracy: 0.85


Random Forest Accuracy: 0.875
13. Use of SciKit Learn tools to implement Decision Tree, Logistic Regression, KNN
Algorithms.

import numpy as np
import [Link] as plt
from sklearn.model_selection import train_test_split
from [Link] import DecisionTreeClassifier
from sklearn.linear_model import LogisticRegression
from [Link] import KNeighborsClassifier
from [Link] import make_classification
from [Link] import accuracy_score

# Generating a synthetic dataset


X, y = make_classification(n_samples=200, n_features=5,
random_state=42)

# Splitting the dataset into training and testing sets


X_train, X_test, y_train, y_test = train_test_split(X, y,
test_size=0.2, random_state=42)

# ----- 1. Decision Tree Classifier -----


dt_model = DecisionTreeClassifier(random_state=42) # Creating model
dt_model.fit(X_train, y_train) # Training model
y_pred_dt = dt_model.predict(X_test) # Making predictions

# ----- 2. Logistic Regression -----


log_reg_model = LogisticRegression(max_iter=200) # Creating model
log_reg_model.fit(X_train, y_train) # Training model
y_pred_lr = log_reg_model.predict(X_test) # Making predictions

# ----- 3. K-Nearest Neighbors (KNN) -----


knn_model = KNeighborsClassifier(n_neighbors=5) # Creating model
knn_model.fit(X_train, y_train) # Training model
y_pred_knn = knn_model.predict(X_test) # Making predictions
# Calculating accuracy for all models
accuracy_dt = accuracy_score(y_test, y_pred_dt)
accuracy_lr = accuracy_score(y_test, y_pred_lr)
accuracy_knn = accuracy_score(y_test, y_pred_knn)

# Printing results
print("Decision Tree Accuracy:", accuracy_dt)
print("Logistic Regression Accuracy:", accuracy_lr)
print("KNN Accuracy:", accuracy_knn)

# Plot feature importance for Decision Tree


feature_importance = dt_model.feature_importances_
[Link](range(len(feature_importance)), feature_importance,
color='green')
[Link]("Feature Index")
[Link]("Importance Score")
[Link]("Feature Importance in Decision Tree")
[Link]()

Decision Tree Accuracy: 0.775


Logistic Regression Accuracy: 0.875
KNN Accuracy: 0.8

You might also like