Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
4 views

Python Practical solution

The document contains a series of Python code snippets demonstrating various programming concepts, including string manipulation, mathematical functions, and matrix operations using libraries like NumPy and SymPy. It features examples of generating sequences, calculating volumes, and implementing numerical methods such as Simpson's rule and the Regula Falsi method. The code is structured in a notebook format, with outputs shown for each executed cell.

Uploaded by

D
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Python Practical solution

The document contains a series of Python code snippets demonstrating various programming concepts, including string manipulation, mathematical functions, and matrix operations using libraries like NumPy and SymPy. It features examples of generating sequences, calculating volumes, and implementing numerical methods such as Simpson's rule and the Regula Falsi method. The code is structured in a notebook format, with outputs shown for each executed cell.

Uploaded by

D
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 54

Slip1 http://localhost:8888/nbconvert/html/Slip1.ipynb?dow...

In [ ]: #Slip 1
#Q1.2

In [1]: string1="python"
>>> print(string1*9)

pythonpythonpythonpythonpythonpythonpythonpythonpython

In [ ]: string="mathematics"
>>> print(string*9)

In [2]: [(n,n*n) for n in range(1,11)]

Out[2]: [(1, 1),


(2, 4),
(3, 9),
(4, 16),
(5, 25),
(6, 36),
(7, 49),
(8, 64),
(9, 81),
(10, 100)]

In [ ]: #Q2.1

In [3]: import numpy as np


>>> print(np.eye(10))

[[1. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 1. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 1. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 1. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 1. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 1. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 1. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 1. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 1. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 1.]]

In [4]: >>> from sympy import*


>>> zeros(7,3)

Out[4]: ⎡0 0 0⎤
⎢0 0 0⎥
⎢ ⎥
⎢0 0⎥
⎢ 0 ⎥
⎢ ⎥
⎢0 0 0⎥
⎢ ⎥
⎢0 0⎥
⎢ 0 ⎥
⎢ ⎥
⎢0 0 0⎥
⎣0 0 0⎦

In [5]: >>> from sympy import*


>>> ones(5,4)

1 of 3 22/11/23, 13:51
Slip1 http://localhost:8888/nbconvert/html/Slip1.ipynb?dow...

Out[5]: ⎡1 1 1 1⎤
⎢1 1 1 1⎥
⎢ ⎥

⎢1 1 1 1⎥

⎢ ⎥
⎢1 1 1 1⎥
⎣1 1 1 1⎦

In [ ]: #Q2.3

In [6]: >>> import math


>>> def phi(n):
... for x in range(1,100):
... if math.gcd(100, x)==1:
... print(x)
...
>>> phi(100)

1
3
7
9
11
13
17
19
21
23
27
29
31
33
37
39
41
43
47
49
51
53
57
59
61
63
67
69
71
73
77
79
81
83
87
89
91
93
97
99

In [ ]: #Q3.a.1

2 of 3 22/11/23, 13:51
Slip1 http://localhost:8888/nbconvert/html/Slip1.ipynb?dow...

In [7]: def simpson13(f,a,b,n):


... h = float(b-a)/n
... result = f(a) + f(b)
... for i in range(1,n):
... k = a + i*h
... if i%2 == 0:
... result = result + 2 * f(k)
... else:
... result = result + 4 * f(k)
... result *= h/3
... return result
...
>>>
>>> def f(x):
... return sin(x)
...
>>> from math import *
>>> simpson13(f,0,pi,6)

Out[7]: 2.0008631896735363

In [ ]: #Q3.b.1

In [8]: def func(x):


return x**3 - 4*x - 9

def regula_falsi(a, b, tol=1e-6, max_iter=100):


if func(a) * func(b) >= 0:
print("The chosen intervals do not bracket the root.")
return None

iteration = 0
while iteration < max_iter:
c = (a * func(b) - b * func(a)) / (func(b) - func(a))

if abs(func(c)) < tol:


print(f"Root found at x = {c} after {iteration} iterations.")
return c

if func(c) * func(a) < 0:


b = c
else:
a = c

iteration += 1

print("Method did not converge within the specified number of iterations."


return None

# Define the initial interval [a, b]


a = 2
b = 3

root = regula_falsi(a, b)

Root found at x = 2.7065279131342495 after 7 iterations.

In [ ]:

3 of 3 22/11/23, 13:51
Untitled33 http://localhost:8888/nbconvert/html/Untitled33.ipyn...

In [4]: #Slip2
#Q1.1

In [5]: import math

def calculate_sphere_volume(radius):
volume = (4/3) * math.pi * (radius ** 3)
return volume
r = 7
sphere_volume = calculate_sphere_volume(r)
print("The volume of the sphere with radius", r, "is:", sphere_volume)

The volume of the sphere with radius 7 is: 1436.7550402417319

In [ ]: #Q1.3

In [6]: for num in range(20, 31):


square = num ** 2
print(f"The square of {num} is: {square}")

The square of 20 is: 400


The square of 21 is: 441
The square of 22 is: 484
The square of 23 is: 529
The square of 24 is: 576
The square of 25 is: 625
The square of 26 is: 676
The square of 27 is: 729
The square of 28 is: 784
The square of 29 is: 841
The square of 30 is: 900

In [ ]: #Q2.1

In [7]: def f(x):


return x**2 - 5*x + 6
result_minus_2 = f(-2)
result_0 = f(0)
result_2 = f(2)
print("f(-2) =", result_minus_2)
print("f(0) =", result_0)
print("f(2) =", result_2)

f(-2) = 20
f(0) = 6
f(2) = 0

In [ ]: #Q2.2

In [8]: def f(x):


return x**3 + 5*x
term_10 = f(10)
print("The 10th term of the sequence is:", term_10)

The 10th term of the sequence is: 1050

In [ ]: #Q3.a.1

1 of 2 22/11/23, 14:26
Untitled33 http://localhost:8888/nbconvert/html/Untitled33.ipyn...

In [9]: def f(x):


return 1 / (1 + x**2)

def simpsons_one_third(a, b, n):


h = (b - a) / n
x = [a + i * h for i in range(n + 1)]
y = [f(val) for val in x]

sum_odd = sum(y[1:-1:2])
sum_even = sum(y[2:-2:2])

integral = h * (y[0] + 4 * sum_odd + 2 * sum_even + y[-1]) / 3


return integral
a = 0
b = 1
n = 4
result = simpsons_one_third(a, b, n)
print("Estimated value of the integral using Simpson's 1/3 rule:", result

Estimated value of the integral using Simpson's 1/3 rule: 0.78539215686274


5

In [ ]: #Q3.b.1

In [10]: def func(x):


return x**3 - 2*x - 5
def regula_falsi(a, b, tol=1e-6, max_iter=100):
if func(a) * func(b) >= 0:
print("The function has the same sign at both ends of the interval."
return None
for i in range(max_iter):
c = (a * func(b) - b * func(a)) / (func(b) - func(a))
if abs(func(c)) < tol:
return c
if func(c) * func(a) < 0:
b = c
else:
a = c
print("Maximum iterations reached.")
return None
a = 2
b = 3
root = regula_falsi(a, b)
if root is not None:
print("Approximate root of the equation x^3 - 2x - 5 = 0 is:", root)
else:
print("Unable to find the root within the specified tolerance and maximum itera

Approximate root of the equation x^3 - 2x - 5 = 0 is: 2.094551398118127

2 of 2 22/11/23, 14:26
In [ ]: #Slip 3
#Q1.1

In [1]: >>> string = "LATEX"


>>> print(string*11)

>>> string = "MATLAB"


>>> print(string*11)

LATEXLATEXLATEXLATEXLATEXLATEXLATEXLATEXLATEXLATEXLATEX
MATLABMATLABMATLABMATLABMATLABMATLABMATLABMATLABMATLABMATLABMATLAB

In [ ]: #Q1.2

In [2]: number = int(input("Enter a number: "))

if number % 2 == 0 and number % 3 == 0 and number % 5 == 0:


print("Number is divisible by 2, 3, and 5")
elif number % 2 == 0 and number % 3 == 0:
print("Number is divisible by 2 and 3")
elif number % 2 == 0 and number % 5 == 0:
print("Number is divisible by 2 and 5")
elif number % 3 == 0 and number % 5 == 0:
print("Number is divisible by 3 and 5")
elif number % 2 == 0:
print("Number is divisible by 2")
elif number % 3 == 0:
print("Number is divisible by 3")
elif number % 5 == 0:
print("Number is divisible by 5")
else:
print("Number is not divisible by 2, 3, or 5")

Enter a number: 5
Number is divisible by 5

In [ ]: #Q2.1

In [4]: >>> from sympy import*


>>> A=Matrix([[3,-2],[6,-4]])
>>> A.eigenvals()
{-1: 1, 0: 1}
>>> A.eigenvects()
[(-1, 1, [Matrix([
[1/2],
[ 1]])]), (0, 1, [Matrix([
[2/3],
[ 1]])])]

Out[4]: [(-1,
1,
[Matrix([
[0.5],
[ 1]])]),
(0,
1,
[Matrix([
[0.666666666666667],
[ 1]])])]

In [ ]: #Q2.2

In [6]: import numpy as np


>>> print(np.eye(10))
[[1. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 1. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 1. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 1. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 1. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 1. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 1. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 1. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 1. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 1.]]

In [7]: >>> from sympy import*


>>> zeros(7,3)

Out[7]: ⎡0 0 0⎤
⎢0 0 0⎥
⎢ ⎥
⎢0 0⎥
⎢ 0 ⎥
⎢ ⎥
⎢0 0 0⎥
⎢ ⎥
⎢0 0⎥
⎢ 0 ⎥
⎢ ⎥
⎢0 0 0⎥
⎣0 0 0⎦

In [9]: >>> from sympy import*


>>> ones(5,4)

Out[9]: ⎡1 1 1 1⎤
⎢1 1 1 1⎥

⎢ ⎥
⎢ 1 1 1 1⎥


⎢1 ⎥
1 1 1⎥
⎣1 1 1 1⎦

In [ ]: #Q3.a.1
In [14]: import numpy as np

def func(x):
return np.sin(x)

def simpsons_one_third(a, b, n):


if n % 2 != 0:
print("Number of intervals must be even for Simpson's 1/3 rule.")
return None

h = (b - a) / n
x = np.linspace(a, b, n+1)
y = func(x)

integral = y[0] + y[n] # Initial and final terms

for i in range(1, n, 2):


integral += 4 * y[i]

for i in range(2, n-1, 2):


integral += 2 * y[i]

integral *= h / 3

return integral

a = 0
b = np.pi
n = 6

estimated_integral = simpsons_one_third(a, b, n)
print(f"The estimated value of the integral using Simpson's 1/3 rule (n={n}) is approxima

The estimated value of the integral using Simpson's 1/3 rule (n=6) is approximately:
2.000863

In [ ]: #Q.3.b.2

In [16]: import math

def f(x):
return 1/(1 + x)

a = 2
b = 10

n = 5

h = (b - a) / n

s = f(a) + f(b)

for i in range(1, n):


s = s + 2 * f(a + i * h)

integral = (h/2) * s

print("The value of integral is: ",integral)

The value of integral is: 1.3206255135651455

In [ ]:
In [ ]: #Slip 4
#Q1.1

In [2]: my_tuple = (5, -3, 0, 1, 6, -6, 2)


ascending_order = tuple(sorted(my_tuple))
descending_order = tuple(sorted(my_tuple, reverse=True))
print(f"Tuple in ascending order: {ascending_order}")
print(f"Tuple in descending order: {descending_order}")

Tuple in ascending order: (-6, -3, 0, 1, 2, 5, 6)


Tuple in descending order: (6, 5, 2, 1, 0, -3, -6)

In [ ]: #Q1.3

In [3]: >>> for i in [1,3,5,7,9,11,13,15,17,19]:


... print(i*i)

1
9
25
49
81
121
169
225
289
361

In [ ]: #Q2.1

In [4]: import numpy as np


>>> print(np.eye(10))

[[1. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 1. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 1. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 1. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 1. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 1. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 1. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 1. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 1. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 1.]]

In [6]: >>> from sympy import*


>>> zeros(7,3)

Out[6]: ⎡0 0 0⎤
⎢0 0 0⎥
⎢ ⎥
⎢0 0⎥
⎢ 0 ⎥
⎢ ⎥
⎢0 0 0⎥
⎢ ⎥
⎢0 0⎥
⎢ 0 ⎥
⎢ ⎥
⎢0 0 0⎥
⎣0 0 0⎦

In [7]: >>> from sympy import*


>>> ones(5,4)
Out[7]: ⎡1 1 1 1⎤
⎢1 1 1 1⎥

⎢1 ⎥
⎢ 1 1 1⎥

⎢ ⎥
⎢1 1 1 1⎥
⎣1 1 1 1⎦

In [ ]: #Q2.2

In [13]: type('number')

Out[13]: str

In [14]: type(31.25)

Out[14]: float

In [15]: type('Mathematics')

Out[15]: str

In [16]: type(49)

Out[16]: int

In [ ]: #Q3.a.1

In [17]: import numpy as np

def func(x):
return x * np.sin(x)

def simpsons_one_third(a, b, n):


if n % 2 != 0:
print("Number of intervals must be even for Simpson's 1/3 rule.")
return None

h = (b - a) / n
x = np.linspace(a, b, n+1)
y = func(x)

integral = y[0] + y[n] # Initial and final terms

for i in range(1, n, 2):


integral += 4 * y[i]

for i in range(2, n-1, 2):


integral += 2 * y[i]

integral *= h / 3

return integral

# Define the limits of integration and the number of intervals


a = 0
b = np.pi
n = 6

estimated_integral = simpsons_one_third(a, b, n)
print(f"The estimated value of the integral using Simpson's 1/3 rule (n={n}) is approxima

The estimated value of the integral using Simpson's 1/3 rule (n=6) is approximately:
3.142949
In [ ]: #Q3.b.1

In [18]: def sieve_of_eratosthenes(n):


primes = [True] * (n + 1)
primes[0] = primes[1] = False

p = 2
while p * p <= n:
if primes[p]:
for i in range(p * p, n + 1, p):
primes[i] = False
p += 1

prime_numbers = [i for i in range(2, n) if primes[i]]


return prime_numbers

# Enter the value of n


given_number = 50 # Change this to any number you prefer

result = sieve_of_eratosthenes(given_number)
print(f"Prime numbers less than {given_number} are: {result}")

Prime numbers less than 50 are: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 4
7]

In [ ]:
In [ ]: #Slip 5
#Q1.2

In [1]: import math


>>> m=[1,2,3,4]
>>> print(m)

[1, 2, 3, 4]

In [2]: import math


>>> l='XYZ'
>>> l='pqr'
>>> print(l)

pqr

In [8]: >>> import math


>>> s='make in india'
>>> print(s)

make in india

In [ ]: #Q1.3

In [9]: >>> import math


>>> print("square root of 21 is:",math.sqrt(21))

square root of 21 is: 4.58257569495584

In [10]: >>> import math


>>> print("square root of 49 is:",math.sqrt(49))

square root of 49 is: 7.0

In [ ]: #Q2.1

In [11]: import numpy as np

matrix_10x10_zeros = np.zeros((10, 10))

print("Matrix 10x10 filled with zeros:")


print(matrix_10x10_zeros)

Matrix 10x10 filled with zeros:


[[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]]

In [14]: import numpy as np

matrix_7x3_zeros = np.zeros((7, 3))

print("Matrix 7x3 filled with zeros:")


print(matrix_7x3_zeros)
Matrix 7x3 filled with zeros:
[[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]]

In [16]: import numpy as np

matrix_5x4_ones = np.ones((5, 4))

print("Matrix 5x4 filled with ones:")


print(matrix_5x4_ones)

Matrix 5x4 filled with ones:


[[1. 1. 1. 1.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]]

In [ ]: #Q2.2

In [18]: from sympy import symbols, linsolve

x, y, z = symbols('x y z')

eq1 = x - 2 * y + 3 * z - 7
eq2 = 2 * x + y + z - 4
eq3 = -3 * x + 2 * y - 2 * z + 10 # Changed the sign to be consistent

solution = linsolve((eq1, eq2, eq3), x, y, z)


print(solution)

{(2, -1, 1)}

In [ ]: #Q3.a.1

In [19]: import numpy as np

A = np.array([[1, 3, 3],
[2, 2, 3],
[4, 2, 1]])

eigenvalues, eigenvectors = np.linalg.eig(A)

print("Eigenvalues:")
print(eigenvalues)
print("\nEigenvectors:")
print(eigenvectors)

P = eigenvectors
D = np.diag(eigenvalues)
diagonalized_matrix = np.dot(np.linalg.inv(P), np.dot(A, P))

print("\nDiagonalized matrix P^-1 * A * P:")


print(diagonalized_matrix)
Eigenvalues:
[ 7. -2. -1.]

Eigenvectors:
[[ 5.77350269e-01 4.08248290e-01 -1.11022302e-16]
[ 5.77350269e-01 4.08248290e-01 -7.07106781e-01]
[ 5.77350269e-01 -8.16496581e-01 7.07106781e-01]]

Diagonalized matrix P^-1 * A * P:


[[ 7.00000000e+00 1.60948057e-15 -4.63718143e-16]
[-4.16132062e-15 -2.00000000e+00 4.24591088e-16]
[-2.94433799e-15 2.23362138e-16 -1.00000000e+00]]

In [ ]: #Q3.b.2

In [20]: def func(x):


return x**3 - 4*x - 9

def regula_falsi(func, a, b, tol=1e-6, max_iter=100):


if func(a) * func(b) >= 0:
print("The method may not converge on the given interval.")
return None

iter_count = 0
while iter_count < max_iter:
c = (a * func(b) - b * func(a)) / (func(b) - func(a))

if abs(func(c)) < tol:


print(f"Root found at x = {c} after {iter_count} iterations.")
return c

if func(c) * func(a) < 0:


b = c
else:
a = c

iter_count += 1

print("The method did not converge within the maximum number of iterations.")
return None

# Initial interval guesses


a = 2
b = 3

root = regula_falsi(func, a, b)

Root found at x = 2.7065279131342495 after 7 iterations.

In [ ]:
slip11 http://localhost:8888/nbconvert/html/slip11.ipynb?do...

In [ ]: Slip No 6
# Q1.2

In [22]: students = [
... {'name': 'John', 'roll_number': 1},
... {'name': 'Steve', 'roll_number': 2},
... {'name': 'Karen', 'roll_number': 3},
... {'name': 'Sophia', 'roll_number': 4},
... {'name': 'Alice', 'roll_number': 5}
... ]
>>> for student in students:
... print(f"Name: {student['name']}, Roll number: {student['roll_number'

Name: John, Roll number: 1


Name: Steve, Roll number: 2
Name: Karen, Roll number: 3
Name: Sophia, Roll number: 4
Name: Alice, Roll number: 5

In [ ]: #Q1.3

In [7]: list1 = [7, 8, 71, 32, 49, -5, 7, 7, 1, 6]


>>> print("Largest element is:",max(list1))

Largest element is: 71

In [8]: print("Smallest element is:",min(list1))

Smallest element is: -5

In [ ]: #Q2.1

In [9]: >>> import numpy as np


>>> Identity_matrix = np.identity(10)
>>> print("Identity Matrix of order 10 is : \n", Identity_matrix)

Identity Matrix of order 10 is :


[[1. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 1. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 1. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 1. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 1. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 1. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 1. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 1. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 1. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 1.]]

In [ ]:

In [10]: determinant = np.linalg.det(Identity_matrix)


>>> print("\nDeterminant of the matrix is:", determinant)

Determinant of the matrix is: 1.0

In [11]: trace = np.trace(Identity_matrix)


>>> print("\nTrace of the matrix is: ", trace)

Trace of the matrix is: 10.0

1 of 2 22/11/23, 13:20
slip11 http://localhost:8888/nbconvert/html/slip11.ipynb?do...

In [14]: >>> transpose = np.transpose(Identity_matrix)


>>> print("\nTranspose of the matrix is",trace)

Transpose of the matrix is 10.0

In [ ]: #Q2.2

In [23]: def f(x,y):


... return x**2 - 2*x*y + 4
...
>>> print(f(2,0))

In [16]: >>> # point (1,-1)


>>> print(f(1,-1))

In [17]: list = []
>>> for x in range(1,201):
... if x % 7 == 0:
... list.append(x)
...
>>> print(list)

[7, 14, 21, 28, 35, 42, 49, 56, 63, 70, 77, 84, 91, 98, 105, 112, 119, 12
6, 133, 140, 147, 154, 161, 168, 175, 182, 189, 196]

In [ ]: #Q3.a.2

In [19]: import numpy as np


>>>
>>> A = np.array([[3,-2],[6,-4]])
>>>
>>> eigen_values, eigen_vectors = np.linalg.eig(A)
>>> D = np.diag(eigen_values)
>>>
>>> P = np.matmul(eigen_vectors, np.linalg.inv(D))
>>>
>>> print("The matrix P is:\n", P)

The matrix P is:


[[ 3.12268450e+14 -4.47213595e-01]
[ 4.68402674e+14 -8.94427191e-01]]

In [20]: print("The diagonal matrix D is:\n", D)

The diagonal matrix D is:


[[ 1.77635684e-15 0.00000000e+00]
[ 0.00000000e+00 -1.00000000e+00]]

In [ ]:

2 of 2 22/11/23, 13:20
Slip 7 http://localhost:8888/nbconvert/html/Slip%207.ipynb...

In [ ]: #Slip 7
#Q1.1

In [1]: # Define the complex numbers


z1 = 5 + 3j
z2 = -5 + 7j

result_a = z1 + z2
print("a. z1 + z2 =", result_a)

result_b = z1 - z2
print("b. z1 - z2 =", result_b)

result_c = z1 * z2
print("c. z1 * z2 =", result_c)

a. z1 + z2 = 10j
b. z1 - z2 = (10-4j)
c. z1 * z2 = (-46+20j)

In [ ]: #Q1.2

In [2]: # Define the strings


string_a = "a. complex number."
string_b = "b. real number"

# Repeat the strings seven times


result_a = string_a * 7
result_b = string_b * 7

print(result_a)
print(result_b)

a. complex number.a. complex number.a. complex number.a. complex number.a.


complex number.a. complex number.a. complex number.
b. real numberb. real numberb. real numberb. real numberb. real numberb. r
eal numberb. real number

In [ ]: #Q2.1

1 of 4 22/11/23, 15:39
Slip 7 http://localhost:8888/nbconvert/html/Slip%207.ipynb...

In [4]: import numpy as np

# Create a 10x10 ones matrix


ones_matrix = np.ones((10, 10))

# Find the determinant


determinant = np.linalg.det(ones_matrix)

# Find the trace


trace = np.trace(ones_matrix)

# Find the transpose


transpose = ones_matrix.T

print("10x10 Ones Matrix:")


print(ones_matrix)
print("\nDeterminant:", determinant)
print("Trace:", trace)
print("\nTranspose:")
print(transpose)

10x10 Ones Matrix:


[[1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]
[1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]
[1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]
[1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]
[1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]
[1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]
[1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]
[1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]
[1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]
[1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]]

Determinant: 0.0
Trace: 10.0

Transpose:
[[1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]
[1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]
[1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]
[1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]
[1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]
[1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]
[1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]
[1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]
[1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]
[1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]]

In [ ]: #Q2.2

2 of 4 22/11/23, 15:39
Slip 7 http://localhost:8888/nbconvert/html/Slip%207.ipynb...

In [ ]: def f(x):
return x**(-4*x-9)

# Calculate f(-1), f(0), f(1)


result_minus_1 = f(-1)
result_0 = f(0)
result_1 = f(1)

print("f(-1) =", result_minus_1)


print("f(0) =", result_0)
print("f(1) =", result_1)

In [ ]: #Q3.a.1

In [7]: def func(x):


return x ** x

def simpsons_one_third(func, a, b, n):


if n % 2 != 0:
print("Number of intervals must be even for Simpson's 1/3 rule.")
return None

h = (b - a) / n
x = a
integral = func(a) + func(b)

for i in range(1, n):


x = a + i * h
coefficient = 4 if i % 2 != 0 else 2
integral += coefficient * func(x)

integral *= h / 3
return integral

# Define the limits and number of intervals


a = 1
b = 5
n = 6 # Number of intervals

integral = simpsons_one_third(func, a, b, n)
print("Approximated integral using Simpson's 1/3 rule:", integral)

Approximated integral using Simpson's 1/3 rule: 1287.0427208512067

In [ ]: #Q3.b.2

3 of 4 22/11/23, 15:39
Slip 7 http://localhost:8888/nbconvert/html/Slip%207.ipynb...

In [8]: def backward_difference(x_vals, y_vals, x):


n = len(x_vals)
if n != len(y_vals) or n < 2:
print("Invalid input")
return None

h = x_vals[1] - x_vals[0]
backward_diff = [y_vals]

for i in range(1, n):


row = []
for j in range(n - i):
row.append(backward_diff[i - 1][j + 1] - backward_diff[i - 1][
backward_diff.append(row)

res = y_vals[-1]
fact = 1
s = (x - x_vals[-1]) / h

for i in range(1, n):


fact *= i
res += (backward_diff[i][n - i - 1] * s) / fact
s *= (s + 1)

return res

X = [0, 1, 2, 3]
Y = [0, 1, 8, 27]

x_val = 2.8

result = backward_difference(X, Y, x_val)


print(f"f({x_val}) using backward difference formula:", result)

f(2.8) using backward difference formula: 22.105599999999995

In [ ]:

4 of 4 22/11/23, 15:39
Untitled27 http://localhost:8888/nbconvert/html/Untitled27.ipyn...

In [ ]: #Slip 8
#Q1.1

In [1]: a = 5
b = 7
c = 9
d = 11
result_1 = a + c
result_2 = a *
result_3 = c ** d
result_4 = a / b
result_5 = a * (b + c)
print(f"a + c = {result_1}")
print(f"a * b = {result_2}")
print(f"c ^ d = {result_3}")
print(f"a / b = {result_4}")
print(f"a * (b + c) = {result_5}")

a + c = 14
a * b = 35
c ^ d = 31381059609
a / b = 0.7142857142857143
a * (b + c) = 80

In [ ]: #Q1.3

In [2]: area = 3.14 * (14 ** 2)

circumference = 2 * 3.14 * 14

print("Area of circle = ", area)


print("Circumference of circle = ", circumference)

Area of circle = 615.44


Circumference of circle = 87.92

In [ ]: #Q2.1

1 of 3 22/11/23, 15:50
Untitled27 http://localhost:8888/nbconvert/html/Untitled27.ipyn...

In [3]: import numpy as np

A = np.array([[1, 2],
[3, 4]])

B = np.array([[5, 6],
[7, 8]])

C = np.array([[9, 10],
[11, 12]])

result1 = np.add(np.add(A, B), C)

result2 = np.add(A, np.add(B, C))

if np.array_equal(result1, result2):
print("(A + B) + C is equal to A + (B + C)")
print("Matrices are associative with respect to addition.")
else:
print("(A + B) + C is NOT equal to A + (B + C)")
print("Matrices are NOT associative with respect to addition.")

(A + B) + C is equal to A + (B + C)
Matrices are associative with respect to addition.

In [ ]: #Q2.2

In [5]: a, b = 0, 1

print(a)
print(b)

for _ in range(8):
c = a + b
print(c)
a, b = b, c

0
1
1
2
3
5
8
13
21
34

In [ ]: #Q3.a.1

2 of 3 22/11/23, 15:50
Untitled27 http://localhost:8888/nbconvert/html/Untitled27.ipyn...

In [6]: def func(x):


return 1 / (1 + x**2)

def simpsons_one_third_rule(func, a, b, n):


h = (b - a) / n
integral = func(a) + func(b)

for i in range(1, n):


if i % 2 == 0:
integral += 2 * func(a + i * h)
else:
integral += 4 * func(a + i * h)

integral *= h / 3
return integral

a = 0
b = 1
n = 6

result = simpsons_one_third_rule(func, a, b, n)
print(f"The estimated value of the integral using Simpson's 1/3 rule with n=6:

The estimated value of the integral using Simpson's 1/3 rule with n=6: 0.7
853979452340107

In [ ]: #Q3.b.2

In [7]: def func(x):


return 2 * x**2 - 4 * x + 1

def trapezoidal_rule(func, a, b, n):


h = (b - a) / n
integral = func(a) + func(b)

for i in range(1, n):


integral += 2 * func(a + i * h)

integral *= h / 2
return integral

a = 2
b = 4
n = 5

result = trapezoidal_rule(func, a, b, n)
print(f"The estimated value of the integral using the trapezoidal rule with n=5:

The estimated value of the integral using the trapezoidal rule with n=5: 1
5.440000000000001

In [ ]:

3 of 3 22/11/23, 15:50
In [ ]: #Slip9
#Q1.2.a

In [1]: import math


sin_30 = math.sin(math.radians(30))
print("Sine of 30 degrees:", sin_30)

Sine of 30 degrees: 0.49999999999999994

In [ ]: #Q1.2.b

In [2]: import math


print("The value of pi is:", math.pi)

The value of pi is: 3.141592653589793

In [ ]: #Q1.2.c

In [4]: import math


print("The value of e is:", math.e)

The value of e is: 2.718281828459045

In [ ]: #Q1.2.d

In [5]: import math


cos_30 = math.cos(math.radians(30))
print("Cosine of 30 degrees:", cos_30)

Cosine of 30 degrees: 0.8660254037844387

In [ ]: #Q1.3

In [6]: numbers = [-10, 10, -1, 1, 0]


modulus_values = [abs(num) for num in numbers]
print("Modulus values:", modulus_values)

Modulus values: [10, 10, 1, 1, 0]

In [ ]: #Q2.1

In [7]: text = 'MATHEMATICS'

second_character = text[1]
fifth_character = text[4]
eighth_character = text[7]
print("Second character:", second_character)
print("Fifth character:", fifth_character)
print("Eighth character:", eighth_character)

Second character: A
Fifth character: E
Eighth character: T

In [ ]: #Q2.3
In [9]: import numpy as np
A = np.array([[2, 3],
[4, 5]])
B = np.array([[1, 0],
[0, 1]])
AB = np.dot(A, B)
AB_inverse = np.linalg.inv(AB)
B_inverse = np.linalg.inv(B)
A_inverse = np.linalg.inv(A)
left_side = AB_inverse
right_side = np.dot(B_inverse, A_inverse)
if np.array_equal(left_side, right_side):
print("(AB)^(-1) = B^(-1) * A^(-1) is verified.")
else:
print("(AB)^(-1) = B^(-1) * A^(-1) is not verified.")

(AB)^(-1) = B^(-1) * A^(-1) is verified.

In [ ]: #Q3.a.2

In [11]: import numpy as np


x = np.array([1, 2, 3, 4])
y = np.array([1, 8, 27, 64])
coefficients = np.polyfit(x, y, len(x) - 1)
poly = np.poly1d(coefficients)
interpolated_value = poly(2.5)
print(f"The interpolated value of f(2.5) is approximately: {interpolated_value}")

The interpolated value of f(2.5) is approximately: 15.624999999999954

In [ ]: #Q3.b.1

In [13]: def f(x):


return x**3 - 4*x - 9
def regula_falsi_method(func, a, b, tolerance, max_iterations):
if func(a) * func(b) >= 0:
return "Root is not within the given interval."
iteration = 0
while iteration < max_iterations:
c = (a * func(b) - b * func(a)) / (func(b) - func(a))
if abs(func(c)) < tolerance:
return round(c, 6)
if func(c) * func(a) < 0:
b = c
else:
a = c
iteration += 1
return "Method did not converge within the given iterations."
a = 2
b = 3
tolerance = 0.000001
max_iterations = 1000
root = regula_falsi_method(f, a, b, tolerance, max_iterations)
print(f"Approximate real root of the equation x^3 - 4x - 9 = 0: {root}")

Approximate real root of the equation x^3 - 4x - 9 = 0: 2.706528

In [ ]:
In [1]: #Slip no 10
#Q.1(1)

In [3]: result_a = 50 % 5 + 11 - (13 + 7) * 10 / 5


print("Result of expression a:", result_a)

result_b = 60 * 20 // 3 + 15 % 3
print("Result of expression b:", result_b)

result_c = 27 - 23 + 8 // 4
print("Result of expression c:", result_c)

Result of expression a: -29.0


Result of expression b: 400
Result of expression c: 6

In [4]: #Q.1(3)

In [5]: base = 10
height = 15

area = 0.5 * base * height

print("The area of the triangle is:", area)

The area of the triangle is: 75.0

In [6]: #Q.2(1)

In [7]: import numpy as np

identity_matrix = np.identity(10)
print("Identity matrix of order 10x10:")
print(identity_matrix)

zero_matrix = np.zeros((7, 3))


print("\nZero matrix of order 7x3:")
print(zero_matrix)

ones_matrix = np.ones((5, 4))


print("\nOnes matrix of order 5x4:")
print(ones_matrix)
Identity matrix of order 10x10:
[[1. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 1. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 1. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 1. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 1. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 1. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 1. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 1. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 1. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 1.]]

Zero matrix of order 7x3:


[[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]]

Ones matrix of order 5x4:


[[1. 1. 1. 1.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]]

In [8]: #Q.2(2)

In [9]: def f(x):


return x**2 + x

start_x = -5
end_x = 5

print("Values of f(x) = x^2 + x for x in the range (-5 <= x <= 5):")
print("x | f(x)")
print("--------------")
for x in range(start_x, end_x + 1):
result = f(x)
print(f"{x} | {result}")

Values of f(x) = x^2 + x for x in the range (-5 <= x <= 5):
x | f(x)
--------------
-5 | 20
-4 | 12
-3 | 6
-2 | 2
-1 | 0
0 | 0
1 | 2
2 | 6
3 | 12
4 | 20
5 | 30

In [10]: #Q.3(A2)
In [11]: from scipy.interpolate import interp1d

x_values = [2, 2.5, 3]


y_values = [0.69315, 0.91629, 1.09861]

interp_func = interp1d(x_values, y_values, kind='linear')

x_interpolated = 2.7
y_interpolated = interp_func(x_interpolated)

print(f"The interpolated value at x = {x_interpolated} is approximately: {y_interpolated

/usr/lib/python3/dist-packages/scipy/__init__.py:146: UserWarning: A NumPy version >=


1.17.3 and <1.25.0 is required for this version of SciPy (detected version 1.26.1
warnings.warn(f"A NumPy version >={np_minversion} and <{np_maxversion}"
The interpolated value at x = 2.7 is approximately: 0.9892180000000002

In [12]: #Q.3(B1)

In [13]: def func(x):


return x**3 - 4*x - 9

def regula_falsi(a, b, tol=1e-6, max_iter=100):


if func(a) * func(b) >= 0:
print("Regula Falsi method fails.")
return None

for i in range(max_iter):
c = (a * func(b) - b * func(a)) / (func(b) - func(a))

if abs(func(c)) < tol:


print(f"Root found at x = {c:.6f} (approx) after {i+1} iterations.")
return c

if func(c) * func(a) < 0:


b = c
else:
a = c

print("Maximum iterations reached. No root found.")


return None

a = 1
b = 3

root = regula_falsi(a, b)

Root found at x = 2.706528 (approx) after 9 iterations.

In [ ]:
In [ ]: #Slip11
#Q1.1.a

In [1]: M = [1, 2, 3, 4, 5, 6, 7]
length_of_M = len(M)
print(f"The length of the list M is: {length_of_M}")

The length of the list M is: 7

In [ ]: #Q1.1.b

In [2]: L = "XY" + "pqr"


print(f"The value of L is: {L}")

The value of L is: XYpqr

In [ ]: #Q1.1.c

In [5]: s = 'Make In India'


substring_1 = s[:5]
substring_2 = s[:9]
print(f"The result of s[:5] is: {substring_1}")
print(f"The result of s[:9] is: {substring_2}")

The result of s[:5] is: Make


The result of s[:9] is: Make In I

In [ ]: #Q1.3

In [6]: S = [3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]


reversed_S = S[::-1]
print(f"The reversed list is: {reversed_S}")

The reversed list is: [13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3]

In [ ]: #Q2.1

In [8]: teachers = {
'Teacher 1': 'Mathematics',
'Teacher 2': 'Physics',
'Teacher 3': 'Biology',
'Teacher 4': 'History',
'Teacher 5': 'Computer Science'
}
print("List of Teachers and Subjects:")
for teacher, subject in teachers.items():
print(f"{teacher} teaches {subject}")

List of Teachers and Subjects:


Teacher 1 teaches Mathematics
Teacher 2 teaches Physics
Teacher 3 teaches Biology
Teacher 4 teaches History
Teacher 5 teaches Computer Science

In [ ]: #Q2.3
In [10]: def is_prime(num):
if num < 2:
return False
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
return False
return True
start = 51
end = 100
print(f"Prime numbers between {start} and {end}:")
for number in range(start, end + 1):
if is_prime(number):
print(number)

Prime numbers between 51 and 100:


53
59
61
67
71
73
79
83
89
97

In [ ]: #Q3.a.2

In [12]: def f(x):


return x**5 + 3*x + 1
def f_prime(x):
return 5*x**4 + 3
def newton_raphson_method(func, func_prime, initial_guess, tolerance, max_iterations):
x = initial_guess
iteration = 0
while iteration < max_iterations:
fx = func(x)
if abs(fx) < tolerance:
return round(x, 4)
derivative = func_prime(x)
if derivative == 0:
return "Derivative is zero. Cannot continue."
x = x - (fx / derivative)
iteration += 1
return "Method did not converge within the given iterations."
initial_guess = -1
tolerance = 0.0001
max_iterations = 1000
root = newton_raphson_method(f, f_prime, initial_guess, tolerance, max_iterations)
print(f"Approximate root of the function within [-2, 0]: {root}")

Approximate root of the function within [-2, 0]: -0.332

In [ ]: #3.b.1
In [14]: def f(x):
return x**3 - 4*x - 9
def regula_falsi_method(func, a, b, tolerance, max_iterations):
if func(a) * func(b) >= 0:
return "Root is not within the given interval."
iteration = 0
while iteration < max_iterations:
c = (a * func(b) - b * func(a)) / (func(b) - func(a))
if abs(func(c)) < tolerance:
return round(c, 6)
if func(c) * func(a) < 0:
b = c
else:
a = c
iteration += 1
return "Method did not converge within the given iterations."
a = 2
b = 3
tolerance = 0.000001
max_iterations = 1000
root = regula_falsi_method(f, a, b, tolerance, max_iterations)
print(f"Approximate real root of the equation x^3 - 4x - 9 = 0: {root}")

Approximate real root of the equation x^3 - 4x - 9 = 0: 2.706528

In [ ]:
In [ ]: #Slip12
#Q1.1.a

In [1]: result = 23 % 2 + 9 - (3 + 7) * 10 / 2
print("Result:", result)

Result: -40.0

In [ ]: #Q1.1.b

In [2]: result = 35 * 10 // 3 + 15 % 3
print("Result:", result)

Result: 116

In [ ]: #Q1.1.c

In [3]: result = 35 - 25 + 4 // 7
print("Result:", result)

Result: 10

In [ ]: #Q1.2

In [4]: number = 25
print("Odd positive integers between 25 and 50:")
while number <= 50:
if number % 2 != 0:
print(number)
number += 1

Odd positive integers between 25 and 50:


25
27
29
31
33
35
37
39
41
43
45
47
49

In [ ]: #Q2.2

In [6]: def product_of_natural_numbers(n):


result = 1
count = 1
while count <= n:
result *= count
count += 1
return result
n = int(input("Enter a positive integer n: "))
if n < 0:
print("Please enter a positive integer.")
else:
product = product_of_natural_numbers(n)
print(f"The product of first {n} natural numbers is:", product)

Enter a positive integer n: 5


The product of first 5 natural numbers is: 120
In [ ]: #Q2.3

In [7]: def is_prime(num):


if num <= 1:
return False
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
return False
return True
print("Prime numbers between 1 and 200:")
for number in range(1, 201):
if is_prime(number):
print(number, end=" ")

Prime numbers between 1 and 200:


2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 101 103 107 109
113 127 131 137 139 149 151 157 163 167 173 179 181 191 193 197 199

In [ ]: #Q3.a.2

In [8]: import numpy as np


matrix = np.array([[3, -2],
[6, -4]])
eigenvalues, eigenvectors = np.linalg.eig(matrix)
P = eigenvectors
print("Matrix of eigenvectors (P):")
print(P)
D = np.diag(eigenvalues)
print("\nDiagonal matrix of eigenvalues (D):")
print(D)

Matrix of eigenvectors (P):


[[0.5547002 0.4472136 ]
[0.83205029 0.89442719]]

Diagonal matrix of eigenvalues (D):


[[ 1.77635684e-15 0.00000000e+00]
[ 0.00000000e+00 -1.00000000e+00]]

In [ ]: #Q3.b.1

In [10]: def f(x):


return x**3 - 2*x - 5
def regula_falsi_method(func, a, b, tolerance, max_iterations):
if func(a) * func(b) >= 0:
return "Root is not within the given interval."
iteration = 0
while iteration < max_iterations:
c = (a * func(b) - b * func(a)) / (func(b) - func(a))
if abs(func(c)) < tolerance:
return round(c, 6)
if func(c) * func(a) < 0:
b = c
else:
a = c
iteration += 1
return "Method did not converge within the given iterations."

a = 2
b = 3
tolerance = 0.000001
max_iterations = 1000
root = regula_falsi_method(f, a, b, tolerance, max_iterations)
print(f"Approximate real root of the equation x^3 - 2x - 5 = 0 within [2, 3]: {root}")
Approximate real root of the equation x^3 - 2x - 5 = 0 within [2, 3]: 2.094551

In [ ]:
In [1]: #Slip No 13
#Q.1(1)

In [2]: z1 = 3 + 2j
z2 = -4 + 1j

addition_result = z1 + z2
print("Addition Result:", addition_result)

subtraction_result = z1 - z2
print("Subtraction Result:", subtraction_result)

multiplication_result = z1 * z2
print("Multiplication Result:", multiplication_result)

Addition Result: (-1+3j)


Subtraction Result: (7+1j)
Multiplication Result: (-14-5j)

In [3]: #Q.1(2)

In [4]: for i in range(1, 11):


square = i ** 2
print(f"The square of {i} is: {square}")

The square of 1 is: 1


The square of 2 is: 4
The square of 3 is: 9
The square of 4 is: 16
The square of 5 is: 25
The square of 6 is: 36
The square of 7 is: 49
The square of 8 is: 64
The square of 9 is: 81
The square of 10 is: 100

In [5]: #Q.2(1)

In [6]: S = [1, 2, 3, 4, 5, 6, 7, 8, 9]

reversed_S = S[::-1]
print("Reversed List:", reversed_S)

Reversed List: [9, 8, 7, 6, 5, 4, 3, 2, 1]

In [7]: #Q.2(3)

In [8]: start_number = 50
end_number = 100

total_sum = sum(range(start_number, end_number + 1))

count_numbers = end_number - start_number + 1

average = total_sum / count_numbers

print("Average of numbers from 50 to 100:", average)

Average of numbers from 50 to 100: 75.0

In [9]: #Q.3(A1)
In [10]: import numpy as np

def f(x):
return np.sqrt(1 + x**3)

def simpsons_one_third_rule(func, a, b, n):


h = (b - a) / n
x = np.linspace(a, b, n+1)
y = func(x)
result = y[0] + y[n]

for i in range(1, n, 2):


result += 4 * y[i]

for i in range(2, n-1, 2):


result += 2 * y[i]

return result * h / 3

a = 0
b = 5
n = 10

integral_estimate = simpsons_one_third_rule(f, a, b, n)
print("Estimated value of the integral:", integral_estimate)

Estimated value of the integral: 23.594609608095343

In [11]: #Q.3(B1)

In [12]: def func(x):


return x**3 - 4*x - 9

def regula_falsi(a, b, tol=1e-6, max_iter=100):


if func(a) * func(b) >= 0:
print("Regula Falsi method fails.")
return None

for i in range(max_iter):
c = (a * func(b) - b * func(a)) / (func(b) - func(a))

if abs(func(c)) < tol:


print(f"Root found at x = {c} (approx) after {i+1} iterations.")
return c

if func(c) * func(a) < 0:


b = c
else:
a = c

print("Maximum iterations reached. No root found.")


return None

a = 1
b = 3

root = regula_falsi(a, b)

Root found at x = 2.7065279352675677 (approx) after 9 iterations.

In [ ]:
In [1]: #slip no 16
#Q.1(1)

In [14]: int_num=-25
float_num=-10.50
print("The absolute value of an integer number is:",abs(int_num))
print("The absolute value of an float number is:",abs(float_num))

The absolute value of an integer number is: 25


The absolute value of an float number is: 10.5

In [15]: #Q.1(2)

In [20]: list1=[5,10,15,20,25,30]
list2=[7,14,21,28,35,42]
list1+list2

Out[20]: [5, 10, 15, 20, 25, 30, 7, 14, 21, 28, 35, 42]

In [21]: 7*list1

Out[21]: [5,
10,
15,
20,
25,
30,
5,
10,
15,
20,
25,
30,
5,
10,
15,
20,
25,
30,
5,
10,
15,
20,
25,
30,
5,
10,
15,
20,
25,
30,
5,
10,
15,
20,
25,
30,
5,
10,
15,
20,
25,
30]
In [22]: 11*list2
Out[22]: [7,
14,
21,
28,
35,
42,
7,
14,
21,
28,
35,
42,
7,
14,
21,
28,
35,
42,
7,
14,
21,
28,
35,
42,
7,
14,
21,
28,
35,
42,
7,
14,
21,
28,
35,
42,
7,
14,
21,
28,
35,
42,
7,
14,
21,
28,
35,
42,
7,
14,
21,
28,
35,
42,
7,
14,
21,
28,
35,
42,
7,
14,
21,
28,
35,
42]

In [23]: #Q.2(1)

In [30]: marks=[70,80,55,78,65]
percentage=(sum(marks)/500)*100
print("Percentage of marks:",percentage)

Percentage of marks: 69.6

In [31]: #Q.2(3)

In [44]: import numpy as np

matrix_A = np.array([[1, 0, 5],


[2, 1, 6],
[3, 4, 0]])

matrix_B = np.array([[2, 5],


[-1, 4]])

det_A = np.linalg.det(matrix_A)
print("Determinant of matrix A:")
print(det_A)

try:
inv_A = np.linalg.inv(matrix_A)
print("\nInverse of matrix A:")
print(inv_A)
except np.linalg.LinAlgError:
print("\nMatrix A is not invertible (singular matrix).")

det_B = np.linalg.det(matrix_B)
print("\nDeterminant of matrix B:")
print(det_B)

try:
inv_B = np.linalg.inv(matrix_B)
print("\nInverse of matrix B:")
print(inv_B)
except np.linalg.LinAlgError:
print("\nMatrix B is not invertible (singular matrix).")

Determinant of matrix A:
0.9999999999999967

Inverse of matrix A:
[[-24. 20. -5.]
[ 18. -15. 4.]
[ 5. -4. 1.]]

Determinant of matrix B:
13.0

Inverse of matrix B:
[[ 0.30769231 -0.38461538]
[ 0.07692308 0.15384615]]

In [41]: #Q.3 A (2)


In [45]: import sympy as sp

x = sp.symbols('x')
f = x**5 + 5*x + 1

f_prime = sp.diff(f, x)

def newton_raphson(func, func_prime, initial_guess, tolerance, max_iterations):


x_n = initial_guess
for i in range(max_iterations):
f_value = func.evalf(subs={x: x_n})
f_prime_value = func_prime.evalf(subs={x: x_n})
if abs(f_value) < tolerance:
return x_n
if f_prime_value == 0:
return "Zero derivative. No solution found."
x_n = x_n - f_value / f_prime_value
return x_n

initial_guess = -0.5
tolerance = 1e-8
max_iterations = 1000

root = newton_raphson(f, f_prime, initial_guess, tolerance, max_iterations)


if isinstance(root, str):
print(root)
else:
print(f"Estimated root: {root}")

Estimated root: -0.199936102171320

In [46]: #Q.3 B (2)

In [47]: def f(x):


return 10 / (1 + x)

def trapezoidal_rule(func, a, b, n):


h = (b - a) / n
result = 0.5 * (func(a) + func(b))
for i in range(1, n):
result += func(a + i * h)
result *= h
return result

a = 1
b = 2
n = 8

integral_value = trapezoidal_rule(f, a, b, n)
print(f"The estimated value of the integral using the Trapezoidal Rule with n={n}: {integ

The estimated value of the integral using the Trapezoidal Rule with n=8: 4.05645851191
1803

In [ ]:
In [ ]: #Slip 18
#Q1.1

In [1]: list1=[16,3,5,48,2,4,5,6,78,12,5,6,24]
>>> print ("smallest element is:",list1[0])

smallest element is: 16

In [ ]: #Q1.2

In [5]: side1 = 12
side2 = 5

hypotenuse = (side1**2 + side2**2)**0.5

print(f"The length of the hypotenuse is: {hypotenuse:.2f}")

The length of the hypotenuse is: 13.00

In [ ]: #Q1.3

In [6]: number = 125312.3142


result = int(number)

print(f"The number with digits after the decimal removed: {result}")

The number with digits after the decimal removed: 125312

In [ ]: #Q2.2

In [7]: n = 1
sum_of_numbers = 0
count = 0

while count < 20:


sum_of_numbers += n
n += 1
count += 1

print(f"The sum of the first twenty natural numbers is: {sum_of_numbers}")

The sum of the first twenty natural numbers is: 210

In [ ]: #Q2.3

In [8]: import numpy as np

A = np.array([[3, -2],
[6, -4]])

eigenvalues, eigenvectors = np.linalg.eig(A)

P = eigenvectors

D = np.diag(eigenvalues)

print("Matrix P (Eigenvectors):")
print(P)

print("\nMatrix D (Diagonal matrix of Eigenvalues):")


print(D)
Matrix P (Eigenvectors):
[[0.5547002 0.4472136 ]
[0.83205029 0.89442719]]

Matrix D (Diagonal matrix of Eigenvalues):


[[ 1.77635684e-15 0.00000000e+00]
[ 0.00000000e+00 -1.00000000e+00]]

In [ ]: #Q3.a.2

In [9]: >>> import scipy.interpolate as interp


>>>
>>> data = {2.0: 2.2, 2.5: 2.6, 3.0: 2.9, 3.5: 3.2}
>>>
>>> x = list(data.keys())
>>> y = list(data.values())
>>>
>>> f = interp.interp1d(x, y, kind='linear')
>>>
>>> x0 = 2.9
>>> y0 = f(x0)
>>>
>>> print("f(2.9) =", y0)

/usr/lib/python3/dist-packages/scipy/__init__.py:146: UserWarning: A NumPy version >=


1.17.3 and <1.25.0 is required for this version of SciPy (detected version 1.26.1
warnings.warn(f"A NumPy version >={np_minversion} and <{np_maxversion}"
f(2.9) = 2.84

In [ ]: #Q3.b.1

In [10]: def func(x):


return x**3 - 5*x - 9

def regula_falsi(a, b, tol=1e-6, max_iter=100):


if func(a) * func(b) >= 0:
print("The chosen intervals do not bracket the root.")
return None

iteration = 0
while iteration < max_iter:
c = (a * func(b) - b * func(a)) / (func(b) - func(a))

if abs(func(c)) < tol:


print(f"Root found at x = {c} after {iteration} iterations.")
return c

if func(c) * func(a) < 0:


b = c
else:
a = c

iteration += 1

print("Method did not converge within the specified number of iterations.")


return None

a = 2
b = 3

root = regula_falsi(a, b)

Root found at x = 2.855196535701404 after 6 iterations.

In [ ]:
Untitled26 http://localhost:8888/nbconvert/html/Untitled26.ipyn...

In [ ]: #slip 19
#Q1.1

In [1]: >>> for i in range(2,11):


... print("Multiplication Table of",i)
... for j in range(1,11):
... print(i,"X",j,"=",i*j)
... print("\n")
...

1 of 6 22/11/23, 14:06
Untitled26 http://localhost:8888/nbconvert/html/Untitled26.ipyn...

Multiplication Table of 2
2 X 1 = 2
2 X 2 = 4
2 X 3 = 6
2 X 4 = 8
2 X 5 = 10
2 X 6 = 12
2 X 7 = 14
2 X 8 = 16
2 X 9 = 18
2 X 10 = 20

Multiplication Table of 3
3 X 1 = 3
3 X 2 = 6
3 X 3 = 9
3 X 4 = 12
3 X 5 = 15
3 X 6 = 18
3 X 7 = 21
3 X 8 = 24
3 X 9 = 27
3 X 10 = 30

Multiplication Table of 4
4 X 1 = 4
4 X 2 = 8
4 X 3 = 12
4 X 4 = 16
4 X 5 = 20
4 X 6 = 24
4 X 7 = 28
4 X 8 = 32
4 X 9 = 36
4 X 10 = 40

Multiplication Table of 5
5 X 1 = 5
5 X 2 = 10
5 X 3 = 15
5 X 4 = 20
5 X 5 = 25
5 X 6 = 30
5 X 7 = 35
5 X 8 = 40
5 X 9 = 45
5 X 10 = 50

Multiplication Table of 6
6 X 1 = 6
6 X 2 = 12
6 X 3 = 18
6 X 4 = 24
6 X 5 = 30
6 X 6 = 36
6 X 7 = 42

2 of 6 22/11/23, 14:06
Untitled26 http://localhost:8888/nbconvert/html/Untitled26.ipyn...

6 X 8 = 48
6 X 9 = 54
6 X 10 = 60

Multiplication Table of 7
7 X 1 = 7
7 X 2 = 14
7 X 3 = 21
7 X 4 = 28
7 X 5 = 35
7 X 6 = 42
7 X 7 = 49
7 X 8 = 56
7 X 9 = 63
7 X 10 = 70

Multiplication Table of 8
8 X 1 = 8
8 X 2 = 16
8 X 3 = 24
8 X 4 = 32
8 X 5 = 40
8 X 6 = 48
8 X 7 = 56
8 X 8 = 64
8 X 9 = 72
8 X 10 = 80

Multiplication Table of 9
9 X 1 = 9
9 X 2 = 18
9 X 3 = 27
9 X 4 = 36
9 X 5 = 45
9 X 6 = 54
9 X 7 = 63
9 X 8 = 72
9 X 9 = 81
9 X 10 = 90

Multiplication Table of 10
10 X 1 = 10
10 X 2 = 20
10 X 3 = 30
10 X 4 = 40
10 X 5 = 50
10 X 6 = 60
10 X 7 = 70
10 X 8 = 80
10 X 9 = 90
10 X 10 = 100

In [ ]: #Q1.3

3 of 6 22/11/23, 14:06
Untitled26 http://localhost:8888/nbconvert/html/Untitled26.ipyn...

In [2]: >>> student_dict = {


... 'John':'May 2, 2000',
... 'Adam':'June 15, 1999',
... 'Sara':'August 23, 1998',
... 'Olivia':'November 18, 2001',
... 'Emily':'January 12, 2003'
... }
>>>
>>> for name, birth_date in student_dict.items():
... print(f'{name} was born on {birth_date}.')
...

John was born on May 2, 2000.


Adam was born on June 15, 1999.
Sara was born on August 23, 1998.
Olivia was born on November 18, 2001.
Emily was born on January 12, 2003.

In [ ]: #Q2.2

In [10]: import numpy as np


import sympy
# Define the matrix A
A = np.array([
[5, 2, 5, 4],
[10, 3, 4, 6],
[2, 0, -1, 11]
])

rref, pivot_columns = sympy.Matrix(A).rref()

print("Row Echelon Form (REF) of A:")


print(rref)

rank = np.linalg.matrix_rank(A)
print(f"\nThe rank of matrix A is: {rank}")

Row Echelon Form (REF) of A:


Matrix([[1, 0, 0, 77/9], [0, 1, 0, -104/3], [0, 0, 1, 55/9]])

The rank of matrix A is: 3

Q2.3

4 of 6 22/11/23, 14:06
Untitled26 http://localhost:8888/nbconvert/html/Untitled26.ipyn...

In [13]: import numpy as np


from scipy.linalg import lu

A = np.array([
[2, -1, 2, 7],
[4, 7, 3, 4],
[4, 2, 0, -1]
])

P, L, U = lu(A)

print("Matrix L:")
print(L)
print("\nMatrix U:")
print(U)

Matrix L:
[[1. 0. 0. ]
[1. 1. 0. ]
[0.5 0.9 1. ]]

Matrix U:
[[ 4. 7. 3. 4. ]
[ 0. -5. -3. -5. ]
[ 0. 0. 3.2 9.5]]

In [ ]: #Q3.a.1

In [14]: angles = [300, 350, 400, 450]


sine_values = [0.5, 0.5736, 0.6428, 0.7071]

def backward_interpolation(x, angles, values):


n = len(angles)
h = angles[1] - angles[0]
p = (x - angles[-1]) / h
result = values[-1]

for i in range(1, n):


temp = 1
for j in range(i):
temp *= (p + j) / (j + 1)
result += temp * values[-(i + 1)]

return result

angle_to_find = 420
sin_42 = backward_interpolation(angle_to_find, angles, sine_values)
print(f"The estimated value of sin(42) is approximately: {sin_42:.4f}")

The estimated value of sin(42) is approximately: 0.2246

In [ ]: #Q3.b.2

5 of 6 22/11/23, 14:06
Untitled26 http://localhost:8888/nbconvert/html/Untitled26.ipyn...

In [15]: angles = [30, 40, 50, 60]


sine_values = [0.5, 0.6428, 0.7660, 0.8660]

def backward_interpolation(x, angles, values):


n = len(angles)
h = angles[1] - angles[0]
p = (x - angles[-1]) / h
result = values[-1]

for i in range(1, n):


temp = 1
for j in range(i):
temp *= (p + j) / (j + 1)
result += temp * values[-(i + 1)]

return result

angle_to_find = 42
sin_42 = backward_interpolation(angle_to_find, angles, sine_values)
print(f"The estimated value of sin(42) is approximately: {sin_42:.4f}")

The estimated value of sin(42) is approximately: -0.0260

In [ ]:

6 of 6 22/11/23, 14:06
Slip 20 http://localhost:8888/nbconvert/html/Slip%2020.ipyn...

In [ ]: #Slip No 20
#Q1.1

In [2]: n = int(input('Please enter a positive integer: '))

for i in range(1, n+1):


print(i, end=' ')
print()

for i in range(1, n+1):


print(i**0.5, end=' ')
print()

Please enter a positive integer: 5


1 2 3 4 5
1.0 1.4142135623730951 1.7320508075688772 2.0 2.23606797749979

In [ ]: #Q1.2

In [3]: sum_of_squares = 0

for i in range(1,26):
sum_of_squares += i**2

print(sum_of_squares)

5525

In [ ]: #Q1.3

In [4]: n = int(input("Enter a number: "))

divisors = []

for i in range(1,n+1):
if n % i == 0:
divisors.append(i)

print("The divisors of",n,"are",divisors)

Enter a number: 5
The divisors of 5 are [1, 5]

In [ ]: #Q2.1

In [5]: tuple = ('I', 'am', 'Indian')

print(tuple[1])

am

In [ ]: #Q2.2

In [6]: import numpy as np

matrix = np.full((4,6), 10)


print(matrix)

1 of 3 22/11/23, 13:42
Slip 20 http://localhost:8888/nbconvert/html/Slip%2020.ipyn...

[[10 10 10 10 10 10]
[10 10 10 10 10 10]
[10 10 10 10 10 10]
[10 10 10 10 10 10]]

In [7]: import numpy as np

matrix = np.array([[3, -2], [6, -4]])

eigenvalues, eigenvectors = np.linalg.eig(matrix)

diagonalize_matrix = np.diag(eigenvalues)

print("Matrix: \n", matrix, "\n")


print("Eigenvalues: \n", eigenvalues, "\n")
print("Eigenvectors: \n", eigenvectors, "\n")
print("Diagonalize matrix: \n", diagonalize_matrix, "\n")

Matrix:
[[ 3 -2]
[ 6 -4]]

Eigenvalues:
[ 1.77635684e-15 -1.00000000e+00]

Eigenvectors:
[[0.5547002 0.4472136 ]
[0.83205029 0.89442719]]

Diagonalize matrix:
[[ 1.77635684e-15 0.00000000e+00]
[ 0.00000000e+00 -1.00000000e+00]]

In [ ]: #Q3.1

In [8]: import math


>>>
>>> def simpsons(f, a, b, n):
... h = (b-a) / n
... s = f(a) + f(b)
... for i in range(1, n, 2):
... s += 4 * f(a + i * h)
... for i in range(2, n-1, 2):
... s += 2 * f(a + i * h)
... return (s * h) / 3
...
>>> def f(x):
... return math.cos(x)
...
>>> a, b = 3, 1
>>> n = 6
>>>
>>> I = simpsons(f, a, b, n)
>>>
>>> print("The value of the integral is", I)

The value of the integral is 0.7003996546766208

In [ ]: #Q3.2

2 of 3 22/11/23, 13:42
Slip 20 http://localhost:8888/nbconvert/html/Slip%2020.ipyn...

In [11]: import numpy as np

x = np.array([1,2,3,6])
y = np.array([2,6,12,42])

xn = 5

coeffs = np.polyfit(x, y, 3)

f = np.poly1d(coeffs)

f_xn = f(xn)

print("Given data:")
print("x:", x)
print("y:", y)
print("xn:", xn)
print("Interpolated value f(xn):", f_xn)

Given data:
x: [1 2 3 6]
y: [ 2 6 12 42]
xn: 5
Interpolated value f(xn): 29.999999999999993

In [ ]: #Q3.b.1

In [12]: def func(x):


return x**3 - 3*x + 2

def trapezoidal_rule(a, b, n):


h = (b - a) / n
integral = 0.5 * (func(a) + func(b)) # Initial and final points
for i in range(1, n):
integral += func(a + i * h)
integral *= h
return integral

a = 1
b = 5
n = 5

estimated_integral = trapezoidal_rule(a, b, n)
print(f"The estimated value of the integral using the Trapezoidal Rule (n=

The estimated value of the integral using the Trapezoidal Rule (n=5) is ap
proximately: 131.8400

In [ ]:

3 of 3 22/11/23, 13:42
In [ ]: #Slip24
#Q1.2

In [1]: def find_remainder(dividend, divisor):


remainder = dividend % divisor
return remainder
dividend = 17
divisor = 5
result = find_remainder(dividend, divisor)
print(f"The remainder after dividing {dividend} by {divisor} is {result}")

The remainder after dividing 17 by 5 is 2

In [ ]: #Q1.3

In [2]: for i in range(1, 51):


if i % 3 == 0 and i % 7 == 0:
print(i)

21
42

In [ ]: #Q2.1

In [3]: for i in range(1, 101):


square_root = i ** 0.5
if square_root.is_integer():
print(f"{i} is a perfect square ({int(square_root)} * {int(square_root)})")

1 is a perfect square (1 * 1)
4 is a perfect square (2 * 2)
9 is a perfect square (3 * 3)
16 is a perfect square (4 * 4)
25 is a perfect square (5 * 5)
36 is a perfect square (6 * 6)
49 is a perfect square (7 * 7)
64 is a perfect square (8 * 8)
81 is a perfect square (9 * 9)
100 is a perfect square (10 * 10)

In [ ]: #Q2.2

In [5]: def check_divisibility_and_range(number):


if number % 5 == 0 and number < 100:
print(f"The number {number} is divisible by 5 and less than 100.")
else:
print(f"The number {number} is either not divisible by 5 or not less than 100."
user_number = int(input("Enter a natural number: "))
check_divisibility_and_range(user_number)

Enter a natural number: 5


The number 5 is divisible by 5 and less than 100.

In [ ]: #Q3.a.2
In [6]: x = [1, 2, 3, 4]
y = [11, 10, 15, 10]
x_value = 1.9
n = len(x)
backward_diff_table = [[0 for _ in range(n)] for _ in range(n)]
for i in range(n):
backward_diff_table[i][0] = y[i]
for i in range(1, n):
for j in range(n - i):
backward_diff_table[j][i] = backward_diff_table[j + 1][i - 1] - backward_diff_tab
def factorial(num):
if num == 0 or num == 1:
return 1
else:
return num * factorial(num - 1)
def backward_difference_interpolation(x, y, x_val):
result = 0
n = len(x)
for i in range(n):
term = backward_diff_table[0][i]
for j in range(i):
term *= (x_val - x[j])
term /= factorial(i)
result += term
return result
result = backward_difference_interpolation(x, y, x_value)
print(f"f({x_value}) ≈ {result}")

f(1.9) ≈ 9.566

In [ ]: #Q3.b.1

In [8]: def f(x):


return x ** 3 - 5 * x - 9
def regula_falsi(a, b, tolerance=1e-8, max_iterations=100):
if f(a) * f(b) >= 0:
print("The chosen interval does not guarantee a root.")
return None
for iteration in range(max_iterations):
c = (a * f(b) - b * f(a)) / (f(b) - f(a))
if abs(f(c)) < tolerance:
print(f"Root found at x = {c} after {iteration + 1} iterations.")
return c
if f(c) * f(a) < 0:
b = c
else:
a = c
print("The method did not converge within the given number of iterations.")
return None
a = 2
b = 4
root = regula_falsi(a, b)
if root is not None:
print(f"Approximate root ≈ {root}")

Root found at x = 2.85519653906505 after 22 iterations.


Approximate root ≈ 2.85519653906505

In [ ]:

You might also like