Python Worksheet
Python Worksheet
INDEX
Exp. List of Experiments Conduct Viva Record Total Remarks
No (M.M:12) (M.M:10) (M.M:8) (M.M:30)
AIM: Implement of Python Basics : Variable, Print Statement, Commands, Data Types : Numeric Types,
string , List and Tuple , Control Structures: If, For and While, Functios: Function
Definition,Function Call,Return Statement,Default Parameters
Introduction: understanding of Python basics, data types, control structures, and functions to build a
strong foundation for programming. Let's break down these concepts and provide a brief review for each.
1. Python Basics:
Variables: In Python, you can create variables to store and manipulate data. Variable names are case-
sensitive.
Comments: Add comments to your code using # for single-line comments or triple-quotes (''' or """) for
multi-line comments.
2. Data Types:
13
List: Ordered, mutable collection.
3. Control Structures:
If Statements:
Loops:
For Loop:
While Loop:
14
Functions in Python:
Function Definition:
Function Call:
Return Statement:
Default Parameters:
Experiment – II: Implementations of different Data Structures in python
Stack:
Code:
class Stack:
self.items = []
def is_empty(self):
return len(self.items) == 0
self.items.append(item)
def pop(self):
if not self.is_empty():
return self.items.pop()
else:
def peek(self):
if not self.is_empty():
return self.items[-1]
else:
def size(self):
return len(self.items)
# Example usage:
stack = Stack()
stack.push(1)
1
stack.push(2)
stack.push(3)
print("Stack:", stack.items)
print("Pop:", stack.pop())
print("Peek:", stack.peek())
Queue:
Code:
class Queue:
self.items = deque()
def is_empty(self):
return len(self.items) == 0
self.items.append(item)
def dequeue(self):
if not self.is_empty():
return self.items.popleft()
else:
def size(self):
return len(self.items)
# Example usage:
queue = Queue()
queue.enqueue(1)
queue.enqueue(2)
queue.enqueue(3)
2
print("Queue:", list(queue.items))
print("Dequeue:", queue.dequeue())
Linked List :
Code:
class Node:
self.data = data
self.next = None
class LinkedList:
self.head = None
def is_empty(self):
new_node = Node(data)
if self.is_empty():
self.head = new_node
else:
current = self.head
while current.next:
current = current.next
current.next = new_node
def display(self):
elements = []
current = self.head
while current:
3
elements.append(current.data)
current = current.next
# Example usage:
linked_list = LinkedList()
linked_list.append(1)
linked_list.append(2)
linked_list.append(3)
linked_list.display()
Experiment–III: Implementing Root-finding Algorithms (Bisection method, Newton-Raphson
method) in Python
S/W Requirement: Python 3.11 (Install latest version according to your system).
Bisection Method:
Code:
raise ValueError("The function values at the interval endpoints must have opposite
signs.") iteration = 0
while (b - a) / 2 > tol and iteration < max_iter:
c = (a + b) / 2
if func(c) == 0:
iteration += 1
return (a + b) / 2
# Example usage:
def quadratic_function(x):
return x**2 - 4
root = bisection_method(quadratic_function, 0, 3)
print("Bisection Method Root:", root)
Newton-Raphson Method:
Code:
iteration += 1
return x
# Example usage:
def cubic_function(x):
Output
Experiment-IV: Implementing Secant Algorithms in Python
S/W Requirement: Python 3.11 (Install latest version according to your system)..
Introduction:
Secant method.
Parameters:
- func: The target function.
- x0: Initial guess for the root.
- x1: Another initial guess for the root.
- tol: Tolerance for stopping criterion (default is 1e-6).
- max_iter: Maximum number of iterations (default is 100).
Returns:
- root: Approximation of the root.
- iterations: Number of iterations performed.
"""
x_k_minus_1 =
x0 x_k = x1
for k in range(max_iter):
f_k_minus_1 = func(x_k_minus_1)
f_k = func(x_k)
x_k_plus_1 = x_k - f_k * (x_k - x_k_minus_1) / (f_k - f_k_minus_1)
if abs(x_k_plus_1 - x_k) < tol:
return x_k_plus_1, k + 1 # Return the root and the number of iterations
x_k_minus_1 = x_k
x_k = x_k_plus_1
raise ValueError("Secant method did not converge within the maximum number of
iterations.")
# Example usage:
if name == " main ":
# Define the function for finding the square root of a
number def target_function(x):
return x**2 - 4
25
# Initial guesses
x0 = 1.0
x1 = 3.0
Output
Experiment-V: Hands-on interpolation exercises using Python libraries
Code:
import numpy as np
from scipy.interpolate import interp1d
import matplotlib.pyplot as plt
In this example, we first generate some sample data with x and y arrays. We then use linear
and cubic spline interpolation with the help of interp1d from SciPy. The interpolated values
are then plotted alongside the original data using Matplotlib.
Feel free to experiment with different kinds of interpolation (e.g., quadratic, polynomial) by
changing the kind parameter in interp1d. You can also try using different sets of data to observe
how the interpolation behaves with various datasets.
Output
Experiment-VI: Implementing numerical integration algorithms.
AIM: implementing two common numerical integration algorithms, the trapezoidal rule and
Simpson's rule
S/W Requirement: Python 3.11 (Install latest version according to your system).
Numerical integration algorithms are used to approximate definite integrals when an analytical
solution is not feasible. Here's a hands-on experiment implementing two common numerical
integration algorithms, the trapezoidal rule and Simpson's rule, in Python:
Code:
import numpy as np
import matplotlib.pyplot as plt
# Function to
integrate def func(x):
return x**2
# Trapezoidal rule implementation
def trapezoidal_rule(func, a, b, n):
h = (b - a) / n
x = np.linspace(a, b, n + 1)
y = func(x)
integral = h * (np.sum(y) - 0.5 * (y[0] + y[-1]))
return integral
# Define integration
bounds a, b = 0, 2
# True integral value for comparison (since we know the integral of x^2 from 0 to
2) true_value = 2.67 # Analytical solution
print(f'True Integral Value: {true_value}')
S/W Requirement: Python 3.11 (Install latest version according to your system).
Code :
import numpy as np
import matplotlib.pyplot as plt
# Function to differentiate
def func(x):
return x**2
# Define parameters
x_value = 2.0
h_values = [0.1, 0.01, 0.001]
Output
Experiment-VIII: Write a program on Lagrange Multipliers in Python
S/W Requirement: Python 3.11 (Install latest version according to your system).
Introduction: simple Python program that demonstrates the use of Lagrange multipliers to
solve a constrained optimization problem. In this example, we'll consider a simple optimization
problem with equality constraints.
Code:
# Lagrangian function
def lagrangian(x, lambda_):
return objective_function(x) + lambda_ * constraint_equation(x)
# Initial guess
initial_guess = [0.5, 0.5]
S/W Requirement: Python 3.11 (Install latest version according to your system).
Introduction: Demonstrates optimization with both equality and inequality constraints using
the scipy.optimize module. In this example, we'll use the minimize function to solve a
constrained optimization problem:
Code:
# Initial guess
initial_guess = [0.5, 0.5]
# Define constraints
constraints = [{'type': 'eq', 'fun': equality_constraint}, {'type': 'ineq', 'fun':
inequality_constraint}]
S/W Requirement: Python 3.11 (Install latest version according to your system).
Python program that uses the Particle Swarm Optimization (PSO) algorithm to optimize a
multidimensional function. In this example, I'll use the pyswarm library, which provides an
implementation of the PSO algorithm.
First, you'll need to install the pyswarm library if you haven't already:
Code:
import numpy as np
from pyswarm import pso
Output