0% found this document useful (0 votes)
182 views

MTC-233 Python Programing Language I Slips Semester III ANSWER

Uploaded by

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

MTC-233 Python Programing Language I Slips Semester III ANSWER

Uploaded by

sawantamruta39
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 169

Savitribai Phule Pune University, PuneBoard of

Studies in Mathematics
S.Y.B.Sc. (Computer Science) Mathematics
Practical Examination
MTC-233: Python Programming Language-I
(CBCS 2019 Pattern)(Semester-III )Slip No.:-1

Time: 3 hour Maximum Marks: 35


Q.1. Attempt any two of the following. [10]
1. Use Python code to evaluate each of the following expression.a. 20 modulus
2 + 7 - (3 +7) × 20 ÷ 2
->result_a = 20 % 2 + 7 - (3 + 7) * 20 / 2
print(result_a)
b. 30 × 10 floor division 3 + 10 modulus 3
->result_b = 30 * 10 // 3 + 10 % 3
print(result_b)
c. 25 - 24 + 4 floor division 4
->result_c = 2**5 - 24 + 4 // 4
print(result_c)
2. Write Python code to repeat the following string 9 times using the string operator‘*’.
a. Python
➔ print("Python" * 9)
b. Mathematics
➔ print("Mathematics" * 9)
3. Write Python program to generate the square of numbers from 1 to 10.
->
squares = [x**2 for x in range(1, 11)]
print(squares)
Q.2. Attempt any two of the following. [10]
1. Using Python code construct the following matrices.
1. An identity matrix of order 10 × 10.
->import numpy as np
identity_matrix = np.eye(10)
print(identity_matrix)

2. Zero matrix of order 7 × 3.


->zero_matrix = np.zeros((7, 3))
print(zero_matrix)
3. Ones matrix of order 5 × 4.
➔ ones_matrix = np.ones((5, 4))
➔ print(ones_matrix)

2. Write Python program to find the 10 term of the sequence of function f (x) = x2 +x.

➔ x = 10
➔ f_x = x**2 + x
➔ print(f_x)
3. Generate all the prime numbers between 1 to 100 using Python code.
➔ 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

➔ primes = [x for x in range(1, 101) if is_prime(x)]


➔ print(primes)
Q.3. a. Attempt any one of the following. [7]
∫π
1. Write Python program to estimate the value of the integral 0 sin(x)dx using Simp-
son’s ( 1 )rd rule (n=6).

import numpy as np

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


h = (b - a) / n
x = np.linspace(a, b, n+1)
y = func(x)
S = y[0] + y[-1] + 4 * sum(y[1:-1:2]) + 2 * sum(y[2:-2:2])
return (h / 3) * S

result = simpsons_rule(np.sin, 0, np.pi, 6)

print(result)
2. Write Python program to evaluate interpolate value f (3) of the given data by La-granges
method.
-> def lagrange_interpolation(x_values, y_values, x):
total = 0
n = len(x_values)

for i in range(n):
term = y_values[i]
for j in range(n
):
if i != j:
term *= (x - x_values[j]) / (x_values[i] - x_values[j])
total += term

return total

x_values = [0, 1, 2, 5]
y_values = [5, 13, 22, 129]
f_3 = lagrange_interpolation(x_values, y_values, 3)
print(f_3)
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune

x 0 1 2 5
Y=f(x) 5 13 22 129

b. Attempt any one of the following. [8]

1. Write Python program to obtained the approximate real root of x3 − 4x − 9 = 0 by


using Regula-falsi method.

->

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

if f(a) * f(b) >= 0:

raise ValueError("The function must have opposite signs at the bounds")

for _ in range(max_iter):

c = (a * f(b) - b * f(a)) / (f(b) - f(a))

if abs(f(c)) < tol:

return c

elif f(a) * f(c) < 0:

b=c

else:

a=c

return c

f = lambda x: x**3 - 4*x - 9

root = regula_falsi(f, 2, 3)

print(root)
∫ 10 1
2. Write Python program to estimate the value of the integral 2 (1+x)
dx using Trape-
zoidal rule (n=8).
->

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


h = (b - a) / n
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune
x = np.linspace(a, b, n + 1)
y = func(x)
return h * (y[0] / 2 + sum(y[1:-1]) + y[-1] / 2)

result = trapezoidal_rule(lambda x: 1 / (1 + x), 2, 10, 8)


print(result)
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune

Savitribai Phule Pune University, Pune


Board of Studies in Mathematics
S.Y.B.Sc. (Computer Science)
Mathematics Practical Examination
MTC-233: Python Programming Language-I
(CBCS 2019 Pattern)(Semester-III )
Slip No.:-2

Time: 3 hour Maximum Marks: 35


Q.1. Attempt any two of the following. [10]
1. Write Python code to calculate the volume of a sphere with radius r = 7 (V = 43πr3).
➔ import math

➔ r=7
➔ volume = (4/3) * math.pi * r**3
➔ print(f"Volume of the sphere: {volume}")

2. Use Python code to construct string operation ‘+’ below string.

a. string1 = Hello, string2 = World!

➔ string1 = "Hello"

➔ string2 = "World!"

➔ result = string1 + ", " + string2

➔ print(result)
b. string1 = Good, string2 = Morning
➔ string1 = "Good"
➔ string2 = "Morning"
➔ result = string1 + " " + string2
➔ print(result)

3. Write Python code to generate the square of numbers from 20 to 30.

➔ for i in range(20, 31):


MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune
➔ print(f"Square of {i}: {i**2}")

Q.2. Attempt any two of the following. [10]

1. Use python code find value of f (−2), f (0), f (2) where f (x) = x2–5x + 6.

➔ def f(x):

➔ return x**2 - 5*x + 6

➔ print(f"f(-2): {f(-2)}")

➔ print(f"f(0): {f(0)}")

➔ print(f"f(2): {f(2)}")

2. Write Python program to find the 10 term of the sequence of function f (x) = x3+5x.

➔ def f(x):

➔ return x**3 + 5*x

➔ n = 10

➔ result = f(n)

➔ print(f"10th term: {result}")

3. Using sympy module of python, find the eigenvalues and corresponding eigenvectors
422
of the matrix A = 2 4 2 .
2 2 4
➔ from sympy import Matrix

➔ A = Matrix([[4, 2, 2], [2, 4, 2], [2, 2, 4]])
➔ eigenvals = A.eigenvals()
➔ eigenvects = A.eigenvects()

➔ print(f"Eigenvalues: {eigenvals}")
➔ print(f"Eigenvectors: {eigenvects}")

Q.3. a. Attempt any one of the following. [7]


∫1 1
1. Write Python program to estimate the value of the integral 0 (1+x2 )
dx using Simp-
son’s ( 31 )rd rule (n=4).
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune
import numpy as np

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

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

integral = (h / 3) * (y[0] + 2 * sum(y[2:n:2]) + 4 * sum(y[1:n:2]) + y[n])


print(f"Estimated value of the integral: {integral}")

2. Write Python program to obtained a real root of f (x) = x3 − 8x − 4 = 0 by using


Newton–Raphson method.

-> def f(x):

return x**3 - 2*x - 5

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

for _ in range(max_iter):

c = (a * f(b) - b * f(a)) / (f(b) - f(a))

if abs(f(c)) < tol:

return c

elif f(a) * f(c) < 0:

b=c

else:

a=c

return c

root = regula_falsi(2, 3)

print(f"Approximate root: {root}")


MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune

b. Attempt any one of the following. [8]

1. Write Python program to obtained the approximate real roots of x3 − 2x − 5 = 0


in [2,3] using Regula-falsi method.

➔ - def lagrange_interpolation(x, y, value):


➔ n = len(x)
➔ result = 0
➔ for i in range(n):
➔ term = y[i]
➔ for j in range(n):
➔ if i != j:
➔ term *= (value - x[j]) / (x[i] - x[j])
➔ result += term
➔ return result

➔ x_vals = [0, 1, 2, 5]
➔ y_vals = [2, 3, 12, 147]

➔ f_3_5 = lagrange_interpolation(x_vals, y_vals, 3.5)
➔ print(f"Interpolated value at x = 3.5: {f_3_5}")
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune

2. Write Python program to evaluate interpolate value f (3.5) of the given data by
Lagranges method.

x 0 1 2 5
Y=f(x) 2 3 12 147

➔ def lagrange_interpolation(x, y, value):


➔ n = len(x)
➔ result = 0
➔ for i in range(n):
➔ term = y[i]
➔ for j in range(n):
➔ if i != j:
➔ term *= (value - x[j]) / (x[i] - x[j])
➔ result += term
➔ return result

➔ x_vals = [0, 1, 2, 5]
➔ y_vals = [2, 3, 12, 147]

➔ f_3_5 = lagrange_interpolation(x_vals, y_vals, 3.5)
➔ print(f"Interpolated value at x = 3.5: {f_3_5}")
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune

Savitribai Phule Pune University, Pune


Board of Studies in Mathematics
S.Y.B.Sc. (Computer Science)
Mathematics Practical Examination
MTC-233: Python Programming Language-I
(CBCS 2019 Pattern)(Semester-III )
Slip No.:-3

Time: 3 hour Maximum Marks: 35


Q.1. Attempt any two of the following. [10]
1. Write python code to test whether given number is divisible by 2 or 3 or 5.
➔ number = int(input("Enter a number: "))
if number % 2 == 0 or number % 3 == 0 or number % 5 == 0:
print(f"{number} is divisible by 2, 3, or 5.")
else:
print(f"{number} is not divisible by 2, 3, or 5.")

2. Repeat the following string 11 times using the string operator ‘*’ on Python.

a. LATEX
b. MATLAB
->
print("LATEX " * 11)
print("MATLAB " * 11)

3. Use Python code to find sum of first thirty natural numbers.

total_sum = sum(range(1, 31))

print("Sum of the first 30 natural numbers is:", total_sum)


Q.2. Attempt any two of the following. [10]
1. Using Python construct the following matrices.

1. An identity matrix of order 10 × 10.


➔ import numpy as np
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune
identity_matrix = np.identity(10)
print(identity_matrix)
2. Zero matrix of order 7 × 3.
➔ zero_matrix = np.zeros((7, 3))
print(zero_matrix)
3. Ones matrix of order 5 × 4.
➔ ones_matrix = np.ones((5, 4))
print(ones_matrix)
2. Using python, find the eigenvalues and corresponding eigenvectors of the matrix
" #
3 −2
.
6 −4
➔ import numpy as np
matrix = np.array([[3, -2], [-2, 3]])
eigenvalues, eigenvectors = np.linalg.eig(matrix)
print("Eigenvalues:", eigenvalues)
print("Eigenvectors:", eigenvectors)

3. Generate all the prime numbers between 1 to 100 using Python code.

-> primes = []

for num in range(2, 101):

is_prime = True

for i in range(2, int(num ** 0.5) + 1):

if num % i == 0:

is_prime = False

break

if is_prime:
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune
primes.append(num)

print("Prime numbers between 1 and 100:", primes)


Q.3. a. Attempt any one of the following. [7]
∫π
1. Write Python program to estimate the value of the integral 0 sin(x)dx using Simp-
son’s ( 1 )rd rule (n=6).


import numpy as np
from scipy.integrate import simps

f = lambda x: np.sin(x)
a, b = 0, np.pi
x = np.linspace(a, b, 100)
y = f(x)
result = simps(y, x)
print("Approximate value of the integral:", result)

2. Write Python program to evaluate third order forward difference of the given data.
x = [0, 1, 2, 3]
y = [1, 0, 1, 10]

# Calculate forward differences


diff1 = [y[i+1] - y[i] for i in range(len(y) - 1)]
diff2 = [diff1[i+1] - diff1[i] for i in range(len(diff1) - 1)]
diff3 = [diff2[i+1] - diff2[i] for i in range(len(diff2) - 1)]
print("Third order forward difference:", diff3)
x 0 1 2 3
Y=f(x) 1 0 1 10
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune

b. Attempt any one of the following. [8]

1. Write Python program to evaluate f(3.5) of the given data.


from scipy.interpolate import interp1d

x = [1, 2, 3, 4, 5]
y = [30, 50, 55, 40, 11]

interpolating_function = interp1d(x, y, kind='linear')


result = interpolating_function(3.5)
print("f(3.5) =", result)
x 1 2 3 4 5
Y=f(x) 30 50 55 40 11
∫ 10 1
2. Write Python program to estimate the value of the integral 2 (1+x)
dx using Trape-
zoidal rule (n=5).
➔ from scipy.integrate import trapezoid

f = lambda x: 1/x
x = np.linspace(1, 10, 100)
y = f(x)
result = trapezoid(y, x)
print("Approximate value of the integral:", result)
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune

Savitribai Phule Pune University, Pune


Board of Studies in Mathematics
S.Y.B.Sc. (Computer Science)
Mathematics Practical Examination
MTC-233: Python Programming Language-I
(CBCS 2019 Pattern)(Semester-III )
Slip No.:-4

Time: 3 hour Maximum Marks: 35


Q.1. Attempt any two of the following. [10]
1. Using python code sort the tuple in ascending and descending order 5, -3, 0, 1, 6,
-6, 2.
-> numbers = (5, -3, 0, 1, 6, -6, 2)
ascending = sorted(numbers)
descending = sorted(numbers, reverse=True)
print("Ascending:", ascending)
print("Descending:", descending)

2. Write python program which deals with concatenation and repetition of lists.
List1 = [15, 20, 25, 30, 35, 40]
List2 = [7, 14, 21, 28, 35, 42]

(a) Find List1 + List2

➔ concatenated_list = List1 + List2 print("List1 + List2:", concatenated_list)


(b) Find 9*List1
➔ repeated_List1 = 9 * List1 print("9 * List1:", repeated_List1)
(c) Find 7*List2
➔ repeated_List2 = 7 * List2 print("7 * List2:", repeated_List2)

3. Write Python code to find the square of odd numbers from 1 to 20 using while loop.

➔ num = 1

while num <= 20:

if num % 2 != 0:

print(f"Square of {num} is {num ** 2}")

num += 1
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune
Q.2. Attempt any two of the following. [10]

1. Using Python construct the following matrices.

1. An identity matrix of order 10 × 10.


➔ import numpy as np

identity_matrix = np.identity(10)
print(identity_matrix)
2. Zero matrix of order 7 × 3.
➔ zero_matrix = np.zeros((7, 3))
print(zero_matrix)
3. Ones matrix of order 5 × 4.
➔ ones_matrix = np.ones((5, 4))
print(ones_matrix)

2. Find the data type of the following data by using Python code.

a. number

-> print(type(5)) # int


b. 31.25
-> print(type(31.25)) # float
c. 8 + 4j
->print(type(8 + 4j)) # complex
d. Mathematics
➔ print(type("Mathematics")) # str
e. 49
➔ print(type(49)) # int

3. Write Python program to find the determinant of matrices


MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune

1 0 5 " #
2 5
A = 2 1 6 and B = .
−1 4
3 4 0

➔ import numpy as np

A = np.array([[1, 0, 5], [2, 1, 6], [3, 4,


0]])
B = np.array([[2, 5], [-1, 4]])

determinant_A = np.linalg.det(A)
determinant_B = np.linalg.det(B)

print("Determinant of A:",
determinant_A)
print("Determinant of B:",
determinant_B)

Q.3. a. Attempt any one of the following. [7]


∫π
1. Write Python program to estimate the value of the integral 0 xsin(x)dx using
Simpson’s ( 1 )rd rule (n=6)

import numpy as np
import numpy
from scipy.integrate as np
import simps
from scipy.integrate
f = lambda x: x * np.sin(x)
import simps
a, b = 0, np.pi
x = np.linspace(a, b, 100)
y = f(x) f = lambda x: x *
result = np.sin(x)
simps(y, x)
print("Approximate value of the integral:", result)
a, b = 0, np.pi
x = np.linspace(a, b,
100)
2. Write Python
y = f(x) program to estimate a root of an equation f (x) = 3x cos(x) 1
using Newton–Raphson
result = simps(y, x)method correct up to four decimal places.
def f(x):
➔print("Approximate
returnvalue
3 * x *ofnp.cos(x)
the -1
integral:", result)
import numpy as np
def f_prime(x):
from scipy.integrate
returnimport
3 * np.cos(x)
simps- 3 * x * np.sin(x)

f = lambda x: x tolerance=1e-4,
def newton_raphson(x0, * max_iterations=100):
np.sin(x)
for _ in range(max_iterations):
a, b = 0, np.pi
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune

x1 = x0 - f(x0) / f_prime(x0)
if abs(x1 - x0) < tolerance:
return round(x1, 4)
x0 = x1
return round(x1, 4)

root = newton_raphson(0.5) # Initial guess − −


print("Estimated root:", root)

b. Attempt any one of the following. [8]

1. Write Python program to find all positive prime numbers less then given number n.
➔ def find_primes(n):

primes = []

for num in range(2, n):

is_prime = True

for i in range(2, int(num ** 0.5) + 1):

if num % i == 0:

is_prime = False

break

if is_prime:

primes.append(num)

return primes

n = int(input("Enter a number: "))

print(f"Prime numbers less than {n}:", find_primes(n))

2. Write Python program to evaluate f(2.5) by forward difference formula of the given
data.

x 0 1 2 3
Y=f(x) 2 1 2 10

➔ x = [0, 1, 2, 3]
y = [2, 1, 2, 10]
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune

# Forward difference calculation


def forward_difference(x, y, value):
n = len(x)
diff_table = [[0 for _ in range(n)] for _ in range(n)]
for i in range(n):
diff_table[i][0] = y[i]
for j in range(1, n):
for i in range(n - j):
diff_table[i][j] = diff_table[i + 1][j - 1] - diff_table[i][j - 1]

# Evaluate f(value) using forward difference formula


result = y[0]
h = x[1] - x[0]
p = (value - x[0]) / h
factorial = 1
for i in range(1, n):
factorial *= i
result += (diff_table[0][i] * (p * (p - 1) * ... * (p - i + 1))) / factorial

return result

value = 2.5
print("f(2.5) =", forward_difference(x, y, value))
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune

Savitribai Phule Pune University, Pune


Board of Studies in Mathematics
S.Y.B.Sc. (Computer Science)
Mathematics Practical Examination
MTC-233: Python Programming Language-I
(CBCS 2019 Pattern)(Semester-III )
Slip No.:-5

Time: 3 hour Maximum Marks: 35


Q.1. Attempt any two of the following. [10]

1. Using sympy module of python find the following for the matrices

−1 1 0 9 0 3
A = 8 5 2 and B = 1 4 1 .
2 −6 2 1 0 −

(a) 2A + B.
(b) 3A – 5B.
(c) A−1.
(d) B3.
(e) AT + BT .

->

from sympy import Matrix


A = Matrix([[-1, 1, 0], [2, -6, 2], [1, 0, -1]])
B = Matrix([[9, 0, 3], [0, 5, 1], [2, -1, 3]])
# (a) 2A + B
result_a = 2 * A + B print("2A + B =", result_a)
# (b) 3A - 5B
result_b = 3 * A - 5 * B print("3A - 5B =", result_b)
# (c) A^(-1)
result_c = A.inv() print("A^(-1) =", result_c)
# (d) B^3
result_d = B ** 3 print("B^3 =", result_d)
# (e) A^T + B^T
result_e = A.T + B.T print("A^T + B^T =", result_e)
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune

2. Evaluate following expression on Python.

(a) M =[1,2,3,4], Find length M.


(b) L=“XYZ”+“pqr”, Find L.
(c) s=‘Make In India’, Find (s[:7]) & (s[:9]).
➔ # (a) Length of M
M = [1, 2, 3, 4]
print("Length of M:", len(M))

# (b) Concatenate strings


L = "XYZ" + "pqr"
print("L:", L)

# (c) Slicing strings


s = 'Make In India'
print("s[:7]:", s[:7])
print("s[:9]:", s[:9])

3. Use Python code to generate the square root of numbers from 21 to 49.

➔ import math

sqrt_values = [math.sqrt(i) for i in range(21, 50)]

print("Square roots from 21 to 49:", sqrt_values)

Q.2. Attempt any two of the following. [10]

1. Using Python construct the following matrices.

1. An identity matrix of order 10 × 10.

➔ import numpy as np

identity_matrix = np.identity(10)

print(identity_matrix)
2. Zero matrix of order 7 × 3.
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune

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


print(zero_matrix)
3. Ones matrix of order 5 × 4.
➔ ones_matrix = np.ones((5, 4))
➔ print(ones_matrix)
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune

2. Using linsolve command in python, solve the following system of linear equations.

x − 2y + 3z = 7
2x + y + z = 4
−3x + 2y − 2z = −10

➔ from sympy import symbols, linsolve

x, y, z = symbols('x y z')
equations = [x - 2*y + 3*z - 7, 2*x + y + z - 4, -3*x + 2*y -
2*z + 10]
solution = linsolve(equations, x, y, z)
print("Solution of the system:", solution)

3. Generate all relatively prime numbers to 111 which are less than 150 using Python
code.

➔ def gcd(a, b):

while b:

a, b = b, a % b

return a

relatively_prime_numbers = [n for n in range(1, 150) if gcd(n, 111) == 1]

print("Relatively prime numbers to 111 less than 150:",


relatively_prime_numbers)

Q.3. a. Attempt any one of the following. [7]

1. Write Python code to find eigenvalues and corresponding eigenvectors of the matrix

1 3 3
A= 2 2 3
4 2 1

and hence find matrix P with diagonalize to A.


MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune
➔ from sympy import Matrix

A = Matrix([[1, 3, 3], [4, 2, 1], [3, 1, 2]])

eigenvalues = A.eigenvals()

eigenvectors = A.eigenvects()

print("Eigenvalues:", eigenvalues)

print("Eigenvectors:", eigenvectors)

P, D = A.diagonalize()

print("Matrix P (eigenvector matrix):", P)

print("Matrix D (diagonal matrix):", D)


2. Write Python program to estimate a root of an equation f (x) = 3x2 + 4x − 10 using
Newton–Raphson method correct up to four decimal places.
->def f(x):
return 3 * x**2 + 4 * x - 10

def f_prime(x):
return 6 * x + 4

def newton_raphson(x0, tolerance=1e-4, max_iterations=100):


for _ in range(max_iterations):
x1 = x0 - f(x0) / f_prime(x0)
if abs(x1 - x0) < tolerance:
return round(x1, 4)
x0 = x1
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune
return round(x1, 4)

root = newton_raphson(1) # Initial guess


print("Estimated root:", root)

b. Attempt any one of the following. [8]

1. Write Python program to obtained the approximate real root of x3 − 4x − 9 = 0 by


using Regula-falsi method.

def f(x):

return x**3 - 4*x - 9

def regula_falsi(a, b, tolerance=1e-4):

if f(a) * f(b) >= 0:

return None # Invalid initial guesses

c=a

while (b - a) >= tolerance:

c = (a * f(b) - b * f(a)) / (f(b) - f(a))

if f(c) == 0.0:

break

elif f(c) * f(a) < 0:

b=c

else:

a=c

return round(c, 4)

root = regula_falsi(2, 3)

print("Approximate real root:", root)


MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune
2. Write Python program to evaluate f(3.5) by forward difference formula of the given
data.

x 1 2 3 4 5
Y=f(x) 41 62 65 50 17

➔ x = [1, 2, 3, 4, 5]
➔ y = [41, 62, 65, 50, 17]

➔ def forward_difference(x, y, value):
➔ n = len(x)
➔ diff_table = [[0 for _ in range(n)] for _ in range(n)]
➔ for i in range(n):
➔ diff_table[i][0] = y[i]
➔ for j in range(1, n):
➔ for i in range(n - j):
➔ diff_table[i][j] = diff_table[i + 1][j - 1] - diff_table[i][j - 1]

➔ result = y[0]
➔ h = x[1] - x[0]
➔ p = (value - x[0]) / h
➔ term = 1
➔ for i in range(1, n):
➔ term *= (p - i + 1) / i
➔ result += term * diff_table[0][i]

➔ return round(result, 4)

➔ print("f(3.5) =", forward_difference(x, y, 3.5))
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune

Savitribai Phule Pune University, Pune


Board of Studies in Mathematics
S.Y.B.Sc. (Computer Science)
Mathematics Practical Examination
MTC-233: Python Programming Language-I
(CBCS 2019 Pattern)(Semester-III )
Slip No.:-6

Time: 3 hour Maximum Marks: 35


Q.1. Attempt any two of the following. [10]
1. Using Python evaluate each of the following expression.

a. 23 modulus 2 + 9 - (3 +7) × 10 ÷ 2
b. 35 × 10 floor division 3 + 15 modulus 3
c. 35 − 25 + 4 floor division 7
-> # (a) 23 modulus 2 + 9 - (3 + 7) × 10 ÷ 2
result_a = 23 % 2 + 9 - (3 + 7) * 10 / 2
print("Result (a):", result_a)

# (b) 35 × 10 floor division 3 + 15 modulus 3


result_b = 35 * 10 // 3 + 15 % 3
print("Result (b):", result_b)

# (c) 35 − 25 + 4 floor division

2. Write Python code to list name and roll number of 5 students in B.Sc.
(Computer science).

->students = [

{"name": "Alice", "roll_number": 101},

{"name": "Bob", "roll_number": 102},

{"name": "Charlie", "roll_number": 103},

{"name": "David", "roll_number": 104},

{"name": "Eva", "roll_number": 105}


MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune
]

for student in students:

print("Name:", student["name"], "| Roll Number:",


student["roll_number"])

3. Write Python code to find maximum and minimum element in the given list.
[7, 8, 71, 32, 49, −5, 7, 7, 0, 1, 6]

->numbers = [7, 8, 71, 32, 49, -5, 7, 7, 0, 1, 6]

max_num = max(numbers)

min_num = min(numbers)

print("Maximum element:", max_num)

print("Minimum element:", min_num)

Q.2. Attempt any two of the following. [10]

1. Using Python code construct identity matrix of order 10 and hence find determinant,
trace and transpose of it.

->import numpy as np

identity_matrix = np.identity(10)

determinant = np.linalg.det(identity_matrix)

trace = np.trace(identity_matrix)

transpose = identity_matrix.T

print("Identity Matrix (10x10):\n", identity_matrix)

print("Determinant:", determinant)

print("Trace:", trace)

print("Transpose:\n", transpose)

2. Write Python code to find the value of function f (x, y) = x2 − 2xy + 4 at the points
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune
(2,0) (1,-1).
➔ def f(x, y):
return x**2 - 2 * x * y + 4

value_1 = f(2, 0)
value_2 = f(1, -1)

print("f(2, 0) =", value_1)


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

3. Find number between 1 to 200 which are divisible by 7 using Python code.

Q.3. a. Attempt any one of the following. [7]



1. Write Python program to estimate the value of the integral 0 π (x − sin(x))dx using
Simpson’s (31 )rd rule (n=5).
➔ import numpy as np

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

a = 0 # Lower limit
b = np.pi # Upper limit
n = 5 # Number of intervals (must be even)
h = (b - a) / n

x = np.linspace(a, b, n + 1)
y = f(x)

integral = h/3 * (y[0] + 2 * sum(y[2:n:2]) + 4 * sum(y[1:n:2]) + y[n])


print("Estimated integral using Simpson's 1/3 rule:", integral)

2. Write Python code to diagonalize matrix

" #
3 −2
A=
6 −4
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune

and find matrix P with diagonalize of A and diagonal matrix D.

from sympy import Matrix

A = Matrix([[3, -2], [-2, 3]])


P, D = A.diagonalize()

print("Matrix P (eigenvector matrix):", P)


print("Diagonal Matrix D:", D)
b. Attempt any one of the following. [8]

1. Write a Python program to obtained the approximate real root of x3 − 2x − 5 = 0


in [2,3] using Regula-falsi method.

➔ def f(x):

return x**3 - 2*x - 5

def regula_falsi(a, b, tolerance=1e-4):

if f(a) * f(b) >= 0:

return None # Invalid initial guesses

c=a

while (b - a) >= tolerance:

c = (a * f(b) - b * f(a)) / (f(b) - f(a))

if f(c) == 0.0:

break

elif f(c) * f(a) < 0:

b=c

else:

a=c
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune
return round(c, 4)

root = regula_falsi(2, 3)

print("Approximate real root:", root)


∫5 1
2. Write a Python program to estimate the value of the integral 1 (1+x) dx using Trape-
zoidal rule (n=10).
➔ def f(x):
return 1 / x

a = 1 # Lower limit
b = 5 # Upper limit
n = 100 # Number of intervals
h = (b - a) / n

x = np.linspace(a, b, n + 1)
y = f(x)

integral = h * (0.5 * y[0] + sum(y[1:-1]) + 0.5 * y[-1])


print("Estimated integral using Trapezoidal rule:", integral)
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune

Savitribai Phule Pune University, Pune


Board of Studies in Mathematics
S.Y.B.Sc. (Computer Science)
Mathematics Practical Examination
MTC-233: Python Programming Language-I
(CBCS 2019 Pattern)(Semester-III )
Slip No.:-7

Time: 3 hour Maximum Marks: 35


Q.1. Attempt any two of the following. [10]
1. Using Python, evaluate the following expression of two complex number z1 = 5 + 3j
and z2 = −5 + 7j

a. z1 + z2
b. z1 − z2
c. z1 ∗ z2
➔ # Define complex numbers
z1 = 5 + 3j
z2 = -5 + 7j

# (a) z1 + z2
sum_result = z1 + z2
print("z1 + z2:", sum_result)

# (b) z1 - z2
diff_result = z1 - z2
print("z1 - z2:", diff_result)

# (c) z1 * z2
prod_result = z1 * z2
print("z1 * z2:", prod_result)

2. Repeat the following string 7 times using the string operator ‘*’ on Python.

a. Complex Number
b. Real Number
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune
➔ # (a) Repeat "Complex Number" 7 times
complex_str = "Complex Number" * 7
print(complex_str)

# (b) Repeat "Real Number" 7 times


real_str = "Real Number" * 7
print(real_str)

3. Write Python code to generate cube of numbers from 1 to 50.

➔ cubes = [i**3 for i in range(1, 51)]

print("Cubes of numbers from 1 to 50:", cubes)

Q.2. Attempt any two of the following. [10]

1. Using Python code construct 0nes matrix of order 10 × 10 and hence find determi-
nant, trace and transpose of it.
➔ import numpy as np

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

# Find determinant (will be zero since it's not invertible)

determinant = np.linalg.det(ones_matrix)

# Find trace (sum of diagonal elements)

trace = np.trace(ones_matrix)

# Find transpose (same for a matrix of ones)

transpose = ones_matrix.T

print("Ones Matrix (10x10):\n", ones_matrix)

print("Determinant:", determinant)

print("Trace:", trace)

print("Transpose:\n", transpose)
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune
2. Write Python code to obtained f (−1), f (0), f (1) of the f (x) = x3 − 4x − 9.
➔ def f(x):
return x**3 - 4*x - 9

f_neg1 = f(-1)
f_0 = f(0)
f_1 = f(1)

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


print("f(0) =", f_0)
print("f(1) =", f_1)

3. Generate all the prime numbers between 500 to 1000 using Python program.

➔ 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

primes = [i for i in range(500, 1001) if is_prime(i)]

print("Prime numbers between 500 and 1000:", primes)

Q.3. a. Attempt any one of the following. [7]


∫5
1. Write Python program to estimate the value of the integral x13dx using Simpson’s
( 1 )rd rule (n=6).

➔ import numpy as np

def f(x):
return x**3
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune

a = 0 # Lower limit
b = 5 # Upper limit
n = 10 # Number of intervals (must be even)
h = (b - a) / n

x = np.linspace(a, b, n + 1)
y = f(x)

integral = h/3 * (y[0] + 2 * sum(y[2:n:2]) + 4 * sum(y[1:n:2]) + y[n])


print("Estimated integral using Simpson's 1/3 rule:", integral)

i
m
2. Writep Python program to evaluate interpolate value f (3) of the given data.
o
r ➔ from scipy.interpolate import lagrange
t
n
u
m
# Givenpdata points
y
x = [0, 1,a 2, 5]
s
y = [2, 3,
n 12, 147]
p

d
# Createe the Lagrange polynomial
f
polynomial
f = lagrange(x, y)
(
x
)
# :
Evaluate the polynomial at x = 3
r
f_3 = polynomial(3)
e
t
print("Interpolated
u value of f(3):", f_3)
r
n
x x 0 1 2 5
* Y=f(x) 2 3 12 147
*
3

a
=
0
#
L
o
w
e
r
l
i
m
i
t
b
=
5
#
U
p
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune

b. Attempt any one of the following. [8]


∫ 10 1
1. Write Python program to estimate the value of the integral 2 (1+x)
dx using Trape-
zoidal rule (n=8).

# Define the function to be integrated


def f(x):
return 1 # The function f(x) = 1 is a constant function

# Trapezoidal Rule implementation


def trapezoidal_rule(a, b, n):
h = (b - a) / n # Calculate the width of each subinterval
integral = 0.5 * (f(a) + f(b)) # Start with the endpoints

for i in range(1, n):


integral += f(a + i * h) # Sum the function values at the intermediate points

integral *= h # Multiply by the width to get the final estimate


return integral

# Parameters for the integral


a = 1 # Lower limit
b = 10 # Upper limit
n = 8 # Number of subintervals

# Estimate the integral


result = trapezoidal_rule(a, b, n)
print("Estimated value of the integral ∫ from 1 to 10 dx using Trapezoidal rule (n=8):", result)

2. Write Python program to evaluate f(2.8) using backward difference formula of the
given data.

x 0 1 2 3
Y=f(x) 1 0 1 10

➔ import numpy as np

# Given data points


x = np.array([0, 1, 2, 3])
y = np.array([1, 0, 1, 10])

# Function to calculate the backward differences


def backward_difference(y, h):
n = len(y)
bd = np.zeros((n, n))
bd[:, 0] = y # First column is the function values

# Calculate backward differences


MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune
for j in range(1, n):
for i in range(n - j):
bd[i][j] = bd[i][j - 1] - bd[i + 1][j - 1]

return bd

# Evaluate f(2.8) using the backward difference formula


def evaluate_at_x(target_x, x, y):
n = len(x)
h = x[1] - x[0] # Assuming uniform spacing
bd = backward_difference(y, h)

# Calculate backward difference interpolation


k = (target_x - x[-1]) / h # Number of intervals back
result = bd[-1][0] # Start with the last function value

for j in range(1, n):


term = bd[-j - 1][j] # Get the j-th backward difference
coeff = 1
for m in range(j):
coeff *= k + m # Product for the coefficient
result += term * coeff / np.math.factorial(j) # Update result

return result

# Target value to evaluate


target_x = 2.8
f_2_8 = evaluate_at_x(target_x, x, y)
print("Estimated value of f(2.8):", f_2_8)
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune

Savitribai Phule Pune University, Pune


Board of Studies in Mathematics
S.Y.B.Sc. (Computer Science)
Mathematics Practical Examination
MTC-233: Python Programming Language-I
(CBCS 2019 Pattern)(Semester-III )
Slip No.:-8

Time: 3 hour Maximum Marks: 35


Q.1. Attempt any two of the following. [10]
1. Use Python code to find a + c, ab, cd, a/b and a(b + c),
where a = 5, b = 7, c = 9, d = 11.
-> # Define the variables
a=5
b=7
c=9
d = 11

# Perform calculations
result_sum = a + c
result_product = a * b
result_cd = c * d
result_division = a / b
result_expression = a * (b + c)

# Print results
print("a + c =", result_sum)
print("ab =", result_product)
print("cd =", result_cd)
print("a/b =", result_division)
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune
print("a(b + c) =", result_expression)

2. The following two statements using the ‘+’string operation on Python.

a. string1 = India Won, string2 = World Cup


b. string1 = God, string2 = is Great
-> # Define the strings
string1_a = "India Won"
string2_a = " World Cup"

# Concatenate strings
result_a = string1_a + string2_a
print(result_a)

string1_b = "God"
string2_b = " is Great"

# Concatenate strings
result_b = string1_b + string2_b
print(result_b)

3. Write Python code to find area and circumference of circle with radius 14.

-> import math

# Define the radius

radius = 14

# Calculate area and circumference

area = math.pi * radius ** 2

circumference = 2 * math.pi * radius

# Print results
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune
print("Area of the circle =", area)

print("Circumference of the circle =", circumference)

Q.2. Attempt any two of the following. [10]

1. Using Python code logically verify associativity of matrices with respective to matrix
addition (use proper matrices).

-> import numpy as np

# Define matrices

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

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

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

# Check associativity: (A + B) + C == A + (B + C)

left_side = np.add(A, B)

left_side = np.add(left_side, C)

right_side = np.add(B, C)

right_side = np.add(A, right_side)

# Print results

print("Left side (A + B) + C:")

print(left_side)

print("Right side A + (B + C):")

print(right_side)
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune
# Verify if they are equal

print("Associativity holds:", np.array_equal(left_side, right_side))

2. Write Python code to generate 10 terms of Fibonacci Sequence using loop.


-> # Initialize variables
n_terms = 10
fibonacci_sequence = []

# Generate Fibonacci sequence


a, b = 0, 1
for _ in range(n_terms):
fibonacci_sequence.append(a)
a, b = b, a + b

# Print the Fibonacci sequence


print("Fibonacci Sequence:", fibonacci_sequence)

3. Using Python code, find determinant and inverse of the matrix if exist.

4 2 2
A = 2 4 2
2 2 4
-> # Define matrix A
A = np.array([[4, 2, 2],
[2, 4, 2],
[2, 2, 4]])

# Calculate determinant
determinant = np.linalg.det(A)

# Calculate inverse if determinant is non-zero


if determinant != 0:
inverse = np.linalg.inv(A)
else:
inverse = None

# Print results
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune
print("Determinant of A =", determinant)
if inverse is not None:
print("Inverse of A:\n", inverse)
else:
print("Inverse does not exist (determinant is zero).")

Q.3. a. Attempt any one of the following. [7]


∫1 1
1. Write Python program to estimate the value of the integral 0 (1+x2 )
dx using Simp-
son’s ( 31 )rd
rule (n=6).
-> import numpy as np

# Function to integrate
def f(x):
return 1 / (1 + 2 * x) # Example function

# Simpson's Rule implementation


def simpsons_rule(a, b, n):
if n % 2 != 0: # n must be even
raise ValueError("n must be even.")

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

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


integral += 4 * f(a + i * h) # Odd terms

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


integral += 2 * f(a + i * h) # Even terms

integral *= h / 3
return integral

# Parameters
a=1
b=1
n=6

# Estimate the integral


result = simpsons_rule(a, b, n)
print("Estimated value of the integral ∫ from 1 to 1/2 dx using Simpson’s rule (n=6):",
result)
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune
2. Write Python program to evaluate fourth order forward difference of the given data.

-> # Given data

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

Y = np.array([41, 62, 65, 50, 17])

# Forward difference calculation

def forward_difference(Y):

n = len(Y)

diff_table = np.zeros((n, n))

diff_table[:, 0] = Y

for j in range(1, n):

for i in range(n - j):

diff_table[i, j] = diff_table[i + 1, j - 1] - diff_table[i, j - 1]

return diff_table

# Calculate forward difference

diff_table = forward_difference(Y)

print("Forward Difference Table:\n", diff_table)


x 1 2 3 4 5
Y=f(x) 41 62 65 50 17
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune

b. Attempt any one of the following. [8]

1. Write Python program to obtained the approximate real root of x3 − 2x − 5 = 0 in


[2,3] using Regula-falsi method.

-> def f(x):

return x**3 - 2*x - 5 # Define the function

def regula_falsi(a, b, tol, max_iter):

if f(a) * f(b) >= 0:

print("The function has the same sign at the endpoints. No root found.")

return None

for i in range(max_iter):

# Calculate the root using the Regula-Falsi formula

c = b - (f(b) * (a - b)) / (f(a) - f(b))

# Check for convergence

if abs(f(c)) < tol:

return c

# Update the endpoints

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

b=c

else:

a=c

print("Max iterations reached. Approximate root:", c)

return c
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune

# Define the interval and parameters

a=2

b=3

tolerance = 1e-6

max_iterations = 100

# Call the function to find the root

root = regula_falsi(a, b, tolerance, max_iterations)

if root is not None:

print("Approximate root:", root)


∫4
2. Write Python program to estimate the value of the integral (2x2 − 4x + 1)dx using
2
Trapezoidal rule (n=5).
-> import numpy as np

def f(x):
return 4 * (2 * x**2 - 4 * x + 1) # Define the function

def trapezoidal_rule(a, b, n):


h = (b - a) / n # Width of each subinterval
integral = 0.5 * (f(a) + f(b)) # Initial area with the endpoints

for i in range(1, n):


integral += f(a + i * h) # Add the area of the intermediate trapezoids

integral *= h # Final area calculation


return integral

# Define the limits and number of subintervals


a = 0 # Lower limit
b = 4 # Upper limit
n = 5 # Number of subintervals
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune
# Estimate the integral
integral_result = trapezoidal_rule(a, b, n)
print("Estimated value of the integral ∫ from 0 to 4 of 4(2x² - 4x + 1) dx:",
integral_result)
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune

Savitribai Phule Pune University, Pune


Board of Studies in Mathematics
S.Y.B.Sc. (Computer Science)
Mathematics Practical Examination
MTC-233: Python Programming Language-I
(CBCS 2019 Pattern)(Semester-III )
Slip No.:-9

Time: 3 hour Maximum Marks: 35


Q.1. Attempt any two of the following. [10]
1. Using Python evaluate each of the following expression.

a. 30 modulus 2 + 7 - (3 +9) × 20 ÷ 5
b. 30 × 10 floor division 3 + 30 modulus 3
c. 55 - 53 + 7 floor division 7
-> import math

# a. Evaluate the expression


expr_a = 30 % 2 + 7 - (3 + 9) * 20 / 5
print("Result of expression a:", expr_a)

# b. Evaluate the expression


expr_b = 30 * 10 // 3 + 30 % 3
print("Result of expression b:", expr_b)

# c. Evaluate the expression


expr_c = 55 - 53 + 7 // 7
print("Result of expression c:", expr_c)

2. Use print command on Python to find

(a) sin30
(b) pi
(c) e
(d) cos30
-> # Use math module for mathematical calculations
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune
print("sin(30 degrees):", math.sin(math.radians(30))) # sin(30)
print("Value of pi:", math.pi) # pi
print("Value of e:", math.e) #e
print("cos(30 degrees):", math.cos(math.radians(30))) # cos(30)

3. Write Python code to generate modulus value of -10 ,10, -1,1,0.

-> # Generate modulus values

values = [-10, 10, -1, 1, 0]

modulus_values = [abs(value) for value in values]

print("Modulus values:", modulus_values)


Q.2. Attempt any two of the following. [10]
1. Use Python code to generate second, fifth, eight characters from string
‘MATHEMATICS ’

-> # Extract specific characters from the string

string = 'MATHEMATICS'

second_char = string[1] # Index 1 for the second character

fifth_char = string[4] # Index 4 for the fifth character

eighth_char = string[7] # Index 7 for the eighth character

print("Second character:", second_char)

print("Fifth character:", fifth_char)

print("Eighth character:", eighth_char)


2. Using python find the eigenvalues and corresponding eigenvectors of the matrix
" #
3 −2
.
6 −4
-> import numpy as np

# Define the matrix


matrix = np.array([[3, -2],
[0, 1]])

# Calculate eigenvalues and eigenvectors


eigenvalues, eigenvectors = np.linalg.eig(matrix)
print("Eigenvalues:", eigenvalues)
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune
print("Eigenvectors:\n", eigenvectors)

3. Write Python code to verify (AB)−1 = B−1A−1 (Use proper matrices A and B).

-> import numpy as np

# Define the matrix

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

[0, 1]])

# Calculate eigenvalues and eigenvectors

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

print("Eigenvalues:", eigenvalues)

print("Eigenvectors:\n", eigenvectors)
Q.3. a. Attempt any one of the following. [7]
∫ 10
1. Write Python program to estimate the value of the integral 1 (x2 + 5x)dx using
Simpson’s ( 1 )rd rule (n=5).

->
from scipy.integrate import quad

# Define the function to integrate


def integrand(x):
return 10 * (x**2 + 5*x)

# Estimate the integral


integral_value, _ = quad(integrand, 0, 1)
print("Estimated value of the integral ∫ from 0 to 1 of 10(x² + 5x) dx:",
integral_value)

2. Write Python program to evaluate interpolate value f (2.5) of the given data.
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune

-> # Given data for interpolation


x_data = np.array([1, 2, 3, 4])
y_data = np.array([1, 8, 27, 64])

# Use numpy's interp function to interpolate


interpolated_value = np.interp(2.5, x_data, y_data)
print("Interpolated value f(2.5):", interpolated_value)
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune

x 1 2 3 4
Y=f(x) 1 8 27 64

b. Attempt any one of the following. [8]

1. Write Python program to obtained the approximate real root of x3 − 4x − 9 = 0 by


using Regula-falsi method.

-> def f(x):

return x**3 - 4*x - 9 # Define the function

def regula_falsi(a, b, tol, max_iter):

if f(a) * f(b) >= 0:

print("No root found in the given interval.")

return None

for i in range(max_iter):

c = b - (f(b) * (a - b)) / (f(a) - f(b))

if abs(f(c)) < tol:

return c

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

b=c

else:

a=c

print("Max iterations reached. Approximate root:", c)

return c

# Define the interval and parameters

a=2
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune
b=3

tolerance = 1e-6

max_iterations = 100

# Call the function to find the root

root = regula_falsi(a, b, tolerance, max_iterations)

if root is not None:

print("Approximate root:", root)

2. Write Python program to evaluate fourth order forward difference of the given data.
-> # Given data
x_data = np.array([1, 2, 3, 4, 5])
y_data = np.array([40, 60, 65, 50, 18])

def forward_difference(x, y):


n = len(y)
diff_table = np.zeros((n, n))
diff_table[:, 0] = y

for j in range(1, n):


for i in range(n - j):
diff_table[i][j] = diff_table[i + 1][j - 1] - diff_table[i][j - 1]

return diff_table

# Calculate forward differences


differences = forward_difference(x_data, y_data)

print("Forward difference table:")


print(differences)
x 1 2 3 4 5
Y=f(x) 40 60 65 50 18
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune

Savitribai Phule Pune University, Pune


Board of Studies in Mathematics
S.Y.B.Sc. (Computer Science)
Mathematics Practical Examination
MTC-233: Python Programming Language-I
(CBCS 2019 Pattern)(Semester-III )
Slip No.:-10

Time: 3 hour Maximum Marks: 35


Q.1. Attempt any two of the following. [10]
1. Using Python evaluate each of the following expression.

a. 50 modulus 5 + 11 - (13 +7) × 10 ÷ 5


b. 60 × 20 floor division 3 + 15 modulus 3
c. 27 - 23 + 8 floor division 4
-> # a. Evaluate the expression
expr_a = 50 % 5 + 11 - (13 + 7) * 10 / 5
print("Result of expression a:", expr_a)

# b. Evaluate the expression


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

# c. Evaluate the expression


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

2. Using Python code


List1 = [5, 10, 15, 20, 25, 30] and List2 = [7, 14, 21, 28, 35, 42]
Evaluate

(a) List1 + List2


(b) 3*List1
(c) 5*List2
-> # Define the lists
List1 = [5, 10, 15, 20, 25, 30]
List2 = [7, 14, 21, 28, 35, 42]
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune

# a. Concatenate List1 and List2


concatenated_list = List1 + List2
print("Concatenated List1 and List2:", concatenated_list)

# b. Multiply List1 by 3
multiplied_list1 = 3 * List1
print("3 times List1:", multiplied_list1)

# c. Multiply List2 by 5
multiplied_list2 = 5 * List2
print("5 times List2:", multiplied_list2)

3. Write Python code to find area of triangle whose base is 10 and height is 15.

-> # Given base and height

base = 10

height = 15

# Calculate the area of the triangle

area = 0.5 * base * height

print("Area of the triangle:", area)


Q.2. Attempt any two of the following. [10]
1. Using Python construct the following matrices.

1. An identity matrix of order 10 × 10.


2. Zero matrix of order 7 × 3.
3. Ones matrix of order 5 × 4.
-> import numpy as np

# 1. Identity matrix of order 10x10


identity_matrix = np.eye(10)
print("Identity matrix (10x10):\n", identity_matrix)
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune
# 2. Zero matrix of order 7x3
zero_matrix = np.zeros((7, 3))
print("Zero matrix (7x3):\n", zero_matrix)

# 3. Ones matrix of order 5x4


ones_matrix = np.ones((5, 4))
print("Ones matrix (5x4):\n", ones_matrix)

2. Write Python program to find the value of function f (x) = x2 + x, (−5 ≤ x ≤ 5).

-> # Define the function f(x) = x^2 + x


def f(x):
return x**2 + x

# Evaluate f(x) for -5 ≤ x ≤ 5


x_values = range(-5, 6)
results = {x: f(x) for x in x_values}
print("Values of f(x) from -5 to 5:", results)
3. Write Python program to find the determinant of matrix

1 0 5 " #
2 5
A = 2 1 6 and B = .
−1 4
3 4 0
# Define matrices A and B
A = np.array([[1, 0, 5],
[2, 1, 6],
[3, 4, 0]])

B = np.array([[2, 5],
[-1, 4]])

# Calculate determinants
det_A = np.linalg.det(A)
det_B = np.linalg.det(B)

print("Determinant of matrix
A:", det_A)
print("Determinant of matrix
B:", det_B)
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune

Q.3. a. Attempt any one of the following. [7]


∫31
1. Write Python program to estimate the value of the integral 1 xdx using Simpson’s
( 1 )rd rule (n=8).
from scipy.integrate import quad

# Define the function to integrate


def integrand(x):
return 1

# Estimate the integral ∫ from 1 to 3 of 1 dx


integral_value, _ = quad(integrand, 1, 3)
print("Estimated value of the integral ∫ from 1 to 3 of 1 dx:",
integral_value)

2. Write Python program to evaluate interpolated value f (2.7) of the given data
f(2)=0.69315,f(2.5)=0.91629,f(3)=1.09861. # Given data for interpolation
3. x_data = [2, 2.5, 3]
4. y_data = [0.69315, 0.91629, 1.09861]
5.
6. # Interpolation using linear interpolation formula
7. def linear_interpolation(x, x_data, y_data):
8. for i in range(len(x_data) - 1):
9. if x_data[i] <= x <= x_data[i + 1]:
10. return y_data[i] + (y_data[i + 1] - y_data[i]) * (x - x_data[i]) /
(x_data[i + 1] - x_data[i])
11. return None
12.
13. # Estimate f(2.7)
14. interpolated_value = linear_interpolation(2.7, x_data, y_data)
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune
15. print("Interpolated value f(2.7):", interpolated_value)->

b. Attempt any one of the following. [8]

1. Write Python program to obtained the approximate real root of x3 − 4x − 9 = 0 by


using Regula-falsi method.

-> def f(x):

return x**3 - 4*x - 9 # Define the function

def regula_falsi(a, b, tol, max_iter):

if f(a) * f(b) >= 0:

print("No root found in the given interval.")

return None

for i in range(max_iter):

c = b - (f(b) * (a - b)) / (f(a) - f(b))

if abs(f(c)) < tol:

return c

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

b=c

else:

a=c

print("Max iterations reached. Approximate root:", c)

return c

# Define the interval and parameters

a=2

b=3
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune
tolerance = 1e-6

max_iterations = 100

# Call the function to find the root

root = regula_falsi(a, b, tolerance, max_iterations)

if root is not None:

print("Approximate root:", root)


∫1
2. Write Python program to estimate the value of the integral cos(x)dx using Trape-
0
zoidal rule (n=5).
-> def trapezoidal_rule(func, a, b, n):
h = (b - a) / n
total = 0.5 * (func(a) + func(b))

for i in range(1, n):


total += func(a + i * h)

return total * h

# Define the function to integrate


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

# Estimate the integral ∫ from 0 to 1 of cos(x) dx using n=5


n=5
trapezoidal_result = trapezoidal_rule(func, 0, 1, n)
print("Estimated value of the integral ∫ from 0 to 1 of cos(x) dx:",
trapezoidal_result)
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune

Savitribai Phule Pune University, Pune


Board of Studies in Mathematics
S.Y.B.Sc. (Computer Science)
Mathematics Practical Examination
MTC-233: Python Programming Language-I
(CBCS 2019 Pattern)(Semester-III )
Slip No.:-11

Time: 3 hour Maximum Marks: 35


Q.1. Attempt any two of the following. [10]
1. Evaluate following expression on Python.

(a) M =[1,2,3,4,5,6,7], Find length M.


(b) L=“XY”+“pqr”, Find L.
(c) s=‘Make In India’, Find (s[:5]) & (s[:9]).
-> # a. Find length of the list M
M = [1, 2, 3, 4, 5, 6, 7]
length_M = len(M)
print("Length of M:", length_M)

# b. Concatenate strings
L = "XY" + "pqr"
print("Value of L:", L)

# c. Find slices of the string


s = 'Make In India'
slice1 = s[:5]
slice2 = s[:9]
print("s[:5]:", slice1)
print("s[:9]:", slice2)

2. Use Python to evaluate expression of the following matrix.

1 1 1
A = 0 1 1
0 0 1
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune
(a) Eigen Value of A.
(b) determinant of A.
(c) inverse of A.
-> import numpy as np

# Define the matrix A


A = np.array([[1, 1, 1],
[0, 1, 1],
[0, 0, 1]])

# a. Eigenvalues of A
eigenvalues = np.linalg.eigvals(A)
print("Eigenvalues of A:", eigenvalues)

# b. Determinant of A
determinant_A = np.linalg.det(A)
print("Determinant of A:", determinant_A)

# c. Inverse of A (if it exists)


try:
inverse_A = np.linalg.inv(A)
print("Inverse of A:\n", inverse_A)
except np.linalg.LinAlgError:
print("Matrix A is singular, so it does not have an inverse.")

3. Write Python code to reverse the string S=[3,4,5,6,7,8,9,10,11,12,13].

-> # Define the list S

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

# Reverse the list S

reversed_S = S[::-1]

print("Reversed list S:", reversed_S)


Q.2. Attempt any two of the following. [10]
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune
1. Using Python code to list Name of 5 teacher in your college with their subject.
-> # List of teachers and their subjects
teachers = [
{"name": "Mr. A", "subject": "Mathematics"},
{"name": "Ms. B", "subject": "Physics"},
{"name": "Mr. C", "subject": "Chemistry"},
{"name": "Ms. D", "subject": "Biology"},
{"name": "Mr. E", "subject": "Computer Science"}
]

# Print the names and subjects


for teacher in teachers:
print(f"Teacher: {teacher['name']}, Subject: {teacher['subject']}")

2. Use linsolve command in python to solve the following system of linear equations.

x − 2y + 3z = 7
2x + y + z = 4
−3x + 2y − 2z = −10
->from sympy import symbols, Eq, linsolve

# Define the variables


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

# Define the equations


eq1 = Eq(x - 2*y + 3*z, 7)
eq2 = Eq(2*x + y + z, 4)
eq3 = Eq(-3*x + 2*y - 2*z, -10)

# Solve the system of equations


solution = linsolve([eq1, eq2, eq3], (x, y, z))
print("Solution of the system of equations:", solution)

3. Generate all the prime numbers between 51 to 100 using Python program.

-> def is_prime(num):

if num < 2:
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune
return False

for i in range(2, int(num ** 0.5) + 1):

if num % i == 0:

return False

return True

# Generate prime numbers between 51 and 100

prime_numbers = [num for num in range(51, 101) if is_prime(num)]

print("Prime numbers between 51 and 100:", prime_numbers)


Q.3. a. Attempt any one of the following. [7]
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune

∫ 10 x
1. Write Python program to estimate the value of the integral 0 e dx using Simpson’s
( 3 )th rule(Take h = 0.5).
->

from scipy.integrate import quad

# Define the function to integrate


def integrand(x):
return np.exp(x)

# Estimate the integral ∫ from 0 to 10 of e^x dx


integral_value, _ = quad(integrand, 0, 10)
8
print("Estimated value of the integral ∫ from 0 to 10 of e^x dx:", integral_value)
2. Write Python program find the approximate root of the function x5 + 3x + 1, in [-2,
0] using Newton Raphson Method correct upto 4 decimal places.
-> def f(x):
return x**5 + 3*x + 1

def f_prime(x):
return 5*x**4 + 3 # Derivative of f

def newton_raphson(x0, tol, max_iter):


for _ in range(max_iter):
x1 = x0 - f(x0) / f_prime(x0)
if abs(x1 - x0) < tol:
return x1
x0 = x1
return None

# Initial guess and parameters


initial_guess = -1 # Starting point in the interval [-2, 0]
tolerance = 1e-4
max_iterations = 100

# Find the root


MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune
root = newton_raphson(initial_guess, tolerance, max_iterations)
print("Approximate root of x^5 + 3x + 1 in [-2, 0]:", root)

b. Attempt any one of the following. [8]

1. Write Python program to obtained the approximate real root of x3 − 4x − 9 = 0 by


using Regula-falsi method.

-> def regula_falsi(a, b, tol, max_iter):

if f(a) * f(b) >= 0:

print("No root found in the given interval.")

return None

for _ in range(max_iter):

c = b - (f(b) * (a - b)) / (f(a) - f(b))

if abs(f(c)) < tol:

return c

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

b=c

else:
a=c

return c

# Define the interval and parameters for Regula-Falsi method

a = 2 # Change as per the equation

b = 3 # Change as per the equation

tolerance = 1e-6

max_iterations = 100
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune
# Find the root using Regula-Falsi method

root_rf = regula_falsi(a, b, tolerance, max_iterations)

if root_rf is not None:

print("Approximate real root of x^3 - 4x - 9 = 0:", root_rf)

2. Write Python program to evaluate interpolate value f (153) of the given data.
-> # Given data for interpolation
x_data = [150, 152, 154, 155]
y_data = [12.247, 12.329, 12.410, 12.490]

# Interpolation using linear interpolation formula


def linear_interpolation(x, x_data, y_data):
for i in range(len(x_data) - 1):
if x_data[i] <= x <= x_data[i + 1]:
return y_data[i] + (y_data[i + 1] - y_data[i]) * (x - x_data[i]) /
(x_data[i + 1] - x_data[i])
return None

# Estimate f(153)
interpolated_value_153 = linear_interpolation(153, x_data, y_data)
print("Interpolated value f(153):", interpolated_value_153)
x 150 152 154 155
Y=f(x) 12.247 12.329 12.410 12.490
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune

Savitribai Phule Pune University, Pune


Board of Studies in Mathematics
S.Y.B.Sc. (Computer Science)
Mathematics Practical Examination
MTC-233: Python Programming Language-I
(CBCS 2019 Pattern)(Semester-III )
Slip No.:-12

Time: 3 hour Maximum Marks: 35


Q.1. Attempt any two of the following. [10]
1. Using Python evaluate each of the following expression.

a. 23 modulus 2 + 9 - (3 +7) × 10 ÷ 2
b. 35 × 10 floor division 3 + 15 modulus 3
c. 35 - 25 + 4 floor division 7
-> # a. Evaluate the expression
expr_a = 23 % 2 + 9 - (3 + 7) * 10 / 2
print("Result of Expression a:", expr_a)

# b. Evaluate the expression


expr_b = 35 * 10 // 3 + 15 % 3
print("Result of Expression b:", expr_b)

# c. Evaluate the expression


expr_c = 35 - 25 + 4 // 7
print("Result of Expression c:", expr_c)

2. Use while command on Python to find odd positive integer between 25 to 50.

-> # Find odd positive integers between 25 and 50 using a while loop
odd_numbers = []
num = 25
while num <= 50:
if num % 2 != 0: # Check if the number is odd
odd_numbers.append(num)
num += 1

print("Odd positive integers between 25 and 50:", odd_numbers)


MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune

4
1 0 5 −1 apply the following operations by using python.
3. For matrix A = 2 1 6 2
3 4 0

a. Delete 2nd row.


b. Delete 1st column.

c. Add column [9, 9] as 2nd column.


-> import numpy as np

# Define the matrix A


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

# a. Delete the 2nd row


A_deleted_row = np.delete(A, 1, axis=0) # Deleting row with index 1
print("Matrix A after deleting 2nd row:\n", A_deleted_row)

# b. Delete the 1st column


A_deleted_column = np.delete(A, 0, axis=1) # Deleting column with index 0
print("Matrix A after deleting 1st column:\n", A_deleted_column)

# c. Add column [9, 9] as the 2nd column


new_column = np.array([[9], [9], [9]])
A_with_new_column = np.insert(A, 1, new_column, axis=1) # Inserting new
column at index 1
print("Matrix A after adding [9, 9] as the 2nd column:\n", A_with_new_column)

Q.2. Attempt any two of the following. [10]


1. Write Python find the eigenvalues and corresponding eigenvectors of the matrix

1 3 3
2 2 3 .

4 2 1
-> # Define the matrix for eigenvalues and
eigenvectors
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune

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

# Calculate eigenvalues and eigenvectors


eigenvalues, eigenvectors = np.linalg.eig(B)
print("Eigenvalues of B:", eigenvalues)
print("Eigenvectors of B:\n", eigenvectors)

2. Write Python program to find the product of n natural numbers using while loop.

-> # Function to find the product of n natural numbers

def product_of_n_natural_numbers(n):

product = 1

count = 1

while count <= n:

product *= count

count += 1

return product

n = 5 # Change n as needed

result = product_of_n_natural_numbers(n)

print(f"Product of first {n} natural numbers:", result)

3. Generate all prime numbers between 1 to 200 using Python code.

-> def is_prime(num):

if num < 2:

return False

for i in range(2, int(num**0.5) + 1):

if num % i == 0:
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune

return False

return True

# Generate prime numbers between 1 and 200

prime_numbers = [num for num in range(1, 201) if is_prime(num)]

print("Prime numbers between 1 and 200:", prime_numbers)


Q.3. a. Attempt any one of the following. [7]
∫π
1. Write Python program to estimate the value of the integral 0 sin(x)dx using Simp-
son’s (31 )rd rule (n=5).

from scipy.integrate import quad


import numpy as np

# Define the function to integrate


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

# Estimate the integral ∫ from 0 to π of sin(x) dx


integral_value, _ = quad(integrand, 0, np.pi)
print("Estimated value of the integral ∫ from 0 to π of
sin(x) dx:", integral_value )
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune

2. Write Python program to diagonalize the matrix

"
3 2#
−6 −4

and find matrix P and D.


-> # Define the matrix for diagonalization
C = np.array([[3, 2],
[6, -4]])

# Calculate eigenvalues and eigenvectors


eigenvalues_C, eigenvectors_C = np.linalg.eig(C)

# Diagonal matrix D
D = np.diag(eigenvalues_C)
P = eigenvectors_C
print("Matrix P (eigenvectors):\n", P)
print("Diagonal matrix D (eigenvalues):\n", D)

b. Attempt any one of the following. [8]

1. Write a Python program to obtained the approximate real root of x3 − 2x − 5 = 0


in [2,3] using Regula-falsi method.

-> def f(x):

return x**3 - 2*x - 5 # Example function

def regula_falsi(a, b, tol, max_iter):

if f(a) * f(b) >= 0:

print("No root found in the given interval.")

return None
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune
for _ in range(max_iter):

c = b - (f(b) * (a - b)) / (f(a) - f(b))

if abs(f(c)) < tol:

return c

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

b=c

else:

a=c

return c

# Define the interval and parameters for Regula-Falsi method

a = 2 # Change as per the equation

b = 3 # Change as per the equation

tolerance = 1e-6

max_iterations = 100

# Find the root using Regula-Falsi method

root_rf = regula_falsi(a, b, tolerance, max_iterations)

if root_rf is not None:

print("Approximate real root of x^3 - 2x - 5 = 0:", root_rf)


∫5 1
2. Write a Python program to estimate the value of the integral 1 (1+x) dx using Trape-
zoidal rule (n=10).
-> # Function for trapezoidal rule
def trapezoidal_rule(f, a, b, n):
h = (b - a) / n
integral = (f(a) + f(b)) / 2
for i in range(1, n):
integral += f(a + i * h)
integral *= h
return integral
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune
# Define the function for integration
def func(x):
return 1 # Function to integrate

# Estimate the integral ∫ from 1 to 5 of dx using trapezoidal rule


a=1
b=5
n=5
trapezoidal_integral = trapezoidal_rule(func, a, b, n)
print("Estimated value of the integral ∫ from 1 to 5 of dx using Trapezoidal rule:",
trapezoidal_integral)
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune

Savitribai Phule Pune University, Pune


Board of Studies in Mathematics
S.Y.B.Sc. (Computer Science)
Mathematics Practical Examination
MTC-233: Python Programming Language-I
(CBCS 2019 Pattern)(Semester-III )
Slip No.:-13

Time: 3 hour Maximum Marks: 35


Q.1. Attempt any two of the following. [10]
1. Using Python code, evaluate the following expression of two complex number z1 =
3 + 2j and z2 = −4 + 1j

a. z1 + z2
b. z1 − z2
c. z1 ∗ z2
-> # Define complex numbers
z1 = 3 + 2j
z2 = -4 + 1j

# a. Addition
addition = z1 + z2
print("z1 + z2 =", addition)

# b. Subtraction
subtraction = z1 - z2
print("z1 - z2 =", subtraction)

# c. Multiplication
multiplication = z1 * z2
print("z1 * z2 =", multiplication)

2. Use Python code to find area and circumference of square whose length is 5.
-> # Define the length of the square
length = 5
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune

# Calculate area and circumference


area = length ** 2
circumference = 4 * length

print("Area of the square:", area)


print("Circumference of the square:", circumference)

3. Write Python program to generate the square number from 1 to 10.

-> # Generate square numbers from 1 to 10

square_numbers = [i**2 for i in range(1, 11)]

print("Square numbers from 1 to 10:", square_numbers)


Q.2. Attempt any two of the following. [10]
1. Write Python code to reverse the string S=[1,2,3,4,5,6,7,8,9].

2. Write Python program to find f (x) = x2 + 3x, Where (−1 ≤ x ≤ 3).

3. Write Python code to find average of number 50 to 100.


Q.3. a. Attempt any one of the following. [7]
∫5 √
1. Write Python program to estimate the value of the integral 0
1 + x3dx using
Simpson’s ( 1 )rd rule (n=10).

3
-> # Reverse the string S
S = [1, 2, 3, 4, 5, 6, 7, 8, 9]
reversed_S = S[::-1]
print("Reversed string S:", reversed_S)
2. Write Python program to evaluate interpolate value f (5.5) of the given data.
-> import numpy as np

# Given data points


x_data = np.array([3, 5, 7, 9])
y_data = np.array([5, 7, 27, 64])
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune
# Linear interpolation function
def linear_interpolation(x, x_data, y_data):
return np.interp(x, x_data, y_data)

# Evaluate f(5.5)
interpolated_value = linear_interpolation(5.5, x_data, y_data)
print("Interpolated value f(5.5):", interpolated_value)
x 3 5 7 9
Y=f(x) 5 7 27 64

b. Attempt any one of the following. [8]


1. Write a Python program to obtained the approximate real root of x3 − 4x − 9 = 0
by using Regula-falsi method.
-> def f(x):
return x**3 - 4*x - 9 # Define the function

def regula_falsi(a, b, tol, max_iter):


if f(a) * f(b) >= 0:
print("No root found in the given interval.")
return None

for _ in range(max_iter):
c = b - (f(b) * (a - b)) / (f(a) - f(b))
if abs(f(c)) < tol:
return c
if f(c) * f(a) < 0:
b=c
else:
a=c

return c
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune

# Define the interval and parameters for Regula-Falsi method


a = 2 # Change as needed
b = 3 # Change as needed
tolerance = 1e-6
max_iterations = 100

# Find the root using Regula-Falsi method


root_rf = regula_falsi(a, b, tolerance, max_iterations)
if root_rf is not None:
print("Approximate real root of x^3 - 4x - 9 = 0:", root_rf)
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune

2. Write a Python program to evaluate f(2.7) by backward difference formula of the


given data.
-> # Given data for backward difference
x_data_diff = np.array([1, 2, 3, 4, 5])
y_data_diff = np.array([40, 60, 65, 50, 18])

# Calculate backward differences


def backward_difference(x_data, y_data, x):
n = len(x_data)
# Find the index of the closest value in x_data that is <= x
idx = np.where(x_data <= x)[0][-1]
if idx == 0:
return None # Cannot calculate backward difference

# Calculate backward difference


h = x_data[1] - x_data[0] # Assuming uniform spacing
f_value = (y_data[idx] - y_data[idx - 1]) / h
return f_value

# Evaluate f(2.7) using backward difference


backward_value = backward_difference(x_data_diff, y_data_diff, 2.7)
if backward_value is not None:
print("Value of f(2.7) using backward difference formula:", backward_value)

x 1 2 3 4 5
Y=f(x) 40 60 65 50 18
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune

Savitribai Phule Pune University, Pune


Board of Studies in Mathematics
S.Y.B.Sc. (Computer Science)
Mathematics Practical Examination
MTC-233: Python Programming Language-I
(CBCS 2019 Pattern)(Semester-III )
Slip No.:-14

Time: 3 hour Maximum Marks: 35


Q.1. Attempt any two of the following. [10]
1. Use print code on Python (a=4,b=6,c=8,d=12).

(a) print(a+c)
(b) print(a*b)
(c) print(c**d)
(d) print(a/b)
(e) Expression: 3 + ( 9 - 2) / 7 * 2 ** 2
➔ # Define the variables
a=4
b=6
c=8
d = 12

# (a) Print a + c
print(a + c)

# (b) Print a * b
print(a * b)

# (c) Print c ** d
print(c ** d)

# (d) Print a / b
print(a / b)
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune
# (e) Evaluate and print the expression
expression_result = 3 + (9 - 2) / 7 * 2 ** 2
print(expression_result)

2. For the following two statements use ‘+’string operation on Python.

a. string1 = Hello, string2 = World!


b. string1 = Good, string2 = Morning
➔ # a. String concatenation
string1_a = "Hello"
string2_a = "World!"
result_a = string1_a + ", " + string2_a
print(result_a)

# b. String concatenation
string1_b = "Good"
string2_b = "Morning"
result_b = string1_b + " " + string2_b
print(result_b)

3. Use Python loop to print(‘Hallo’,i,‘You Learn Python’)


where i = [‘Saurabh’,‘Akash’,‘Sandeep’,‘Ram’,‘Sai’]

➔ # List of names

names = ['Saurabh', 'Akash', 'Sandeep', 'Ram', 'Sai']

# Loop through the names and print the greeting

for i in names:

print(f'Hallo {i}, You Learn Python')

Q.2. Attempt any two of the following. [10]

1. Using Python code construct any two matrices A and B

1. Show that A+B=B+A.


2. Find A-B.
-> import numpy as np
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune
# Define two matrices A and B
A = np.array([[1, 2], [3, 4]])
B = np.array([[5, 6], [7, 8]])

# 1. Show that A + B = B + A
addition_commutative = np.array_equal(A + B, B + A)
print("A + B = B + A:", addition_commutative)

# 2. Find A - B
difference = A - B
print("A - B:\n", difference)

2. Write Python program to find the sequence of function f (x) = x + 5, (−5 ≤ x ≤ 5)

-> # Define the function


def f(x):
return x + 5

# Generate the sequence for -5 ≤ x ≤ 5


sequence = {x: f(x) for x in range(-5, 6)}
print("Sequence of f(x) = x + 5 for -5 ≤ x ≤ 5:", sequence)
3. Using sympy module of python find the eigenvalues and corresponding eigenvectors
of the matrix

4 2 2
A = 2 4 2 .
2 2 4

-> import sympy as sp

# Define the matrix


matrix = sp.Matrix([[4, 2, 2], [2, 2, 4], [0, 0, 1]])

# Calculate eigenvalues and eigenvectors


eigenvalues = matrix.eigenvals()
eigenvectors = matrix.eigenvects()

print("Eigenvalues:", eigenvalues)
print("Eigenvectors:", eigenvectors)
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune

Q.3. a. Attempt any one of the following. [7]


∫1 1
1. Write a Python program to estimate the value of the integral 0 (1+x 2)
dx using
Simpson’s (31 )rd
rule (n=4)
-
-> from scipy.integrate import simpson
import numpy as np

# Define the function to integrate


def integrand(x):
return x**2 # Example function

# Create an array of x values for n=4 (4 intervals)


x_values = np.linspace(1, 2, 5) # 5 points for n=4
y_values = integrand(x_values)

# Estimate the integral using Simpson's rule


integral_value = simpson(y_values, x_values)
print("Estimated value of the integral ∫ from 1 to 2 of x^2 dx using Simpson's rule:",
integral_value)

2. Write a Python program to obtained a real root of f (x) = x3 − 8x − 4 = 0 using


Newton–Raphson method.

-> def f(x):

return x**3 - 8*x - 4 # Define the function

def f_prime(x):

return 3*x**2 - 8 # Derivative of the function

def newton_raphson(initial_guess, tol, max_iter):

x = initial_guess

for _ in range(max_iter):

x_new = x - f(x) / f_prime(x)

if abs(x_new - x) < tol:

return x_new
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune
x = x_new

return None

# Parameters for Newton-Raphson method

initial_guess = 2

tolerance = 1e-6

max_iterations = 100

# Find the root using Newton-Raphson method

root_newton = newton_raphson(initial_guess, tolerance, max_iterations)

if root_newton is not None:

print("Approximate real root of f(x) = x^3 - 8x - 4 =", root_newton)

b. Attempt any one of the following. [8]

1. Write Python program to obtained the approximate real root of x3 − 2x − 5 = 0 in


[2,3] using Regula-falsi method.

-> def regula_falsi(a, b, tol, max_iter):

if f(a) * f(b) >= 0:

print("No root found in the given interval.")

return None

for _ in range(max_iter):

c = b - (f(b) * (a - b)) / (f(a) - f(b))

if abs(f(c)) < tol:

return c

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

b=c

else:
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune
a=c

return c

# Define the interval and parameters for Regula-Falsi method

a_rf = 2 # Change as needed

b_rf = 3 # Change as needed

tolerance_rf = 1e-6

max_iterations_rf = 100

# Find the root using Regula-Falsi method

root_rf = regula_falsi(a_rf, b_rf, tolerance_rf, max_iterations_rf)

if root_rf is not None:

print("Approximate real root of x^3 - 2x - 5 = 0:", root_rf)

2. Write Python program to evaluate approximate value of f(1.5) by using forward


difference formula of the given data.

-> # Given data for forward difference

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

y_data_diff = np.array([30, 50, 65, 40, 18])

# Calculate forward differences

def forward_difference(x_data, y_data, x):

# Assuming uniform spacing

h = x_data[1] - x_data[0]

idx = np.where(x_data == x)[0][0]

if idx == len(y_data) - 1:

return None # Cannot calculate forward difference at last point


MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune
return (y_data[idx + 1] - y_data[idx]) / h

# Evaluate f(1.5) using forward difference

forward_value = forward_difference(x_data_diff, y_data_diff, 1)

if forward_value is not None:

print("Value of f(1.5) using forward difference formula:", forward_value)

x 1 2 3 4 5
Y=f(x) 30 50 65 40 18
.
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune

Savitribai Phule Pune University, Pune


Board of Studies in Mathematics
S.Y.B.Sc. (Computer Science)
Mathematics Practical Examination
MTC-233: Python Programming Language-I
(CBCS 2019 Pattern)(Semester-III )
Slip No.:-15

Time: 3 hour Maximum Marks: 35


Q.1. Attempt any two of the following. [10]
1. Using for loop on Python, find range from 1 to 11 integers.
-> # Using a for loop to print integers from 1 to 11
for i in range(1, 12):
print(i)

2. Use Python code to find,

(a) sin75
(b) pi/2
(c) e
(d) cos56
-> import math

# (a) Calculate sin(75 degrees)


sin_75 = math.sin(math.radians(75))
print("sin(75):", sin_75)

# (b) Calculate π/2


pi_over_2 = math.pi / 2
print("π/2:", pi_over_2)

# (c) Calculate e
e_value = math.e
print("e:", e_value)
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune

# (d) Calculate cos(56 degrees)


cos_56 = math.cos(math.radians(56))
print("cos(56):", cos_56)

3. Write Python program to find diameter, area, circumference of the circle with radius
is 5.

-> # Given radius

radius = 5

# Calculate diameter, area, and circumference

diameter = 2 * radius

area = math.pi * radius ** 2

circumference = 2 * math.pi * radius

# Print results

print("Diameter:", diameter)

print("Area:", area)

print("Circumference:", circumference)

Q.2. Attempt any two of the following. [10]

1. Using Python code construct any three matrices A,B and C to show that
(A+B)+C=A+(B+C).

-> import numpy as np

# Define matrices A, B, and C

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

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

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


MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune

# Check (A + B) + C

left_side = A + B + C

# Check A + (B + C)

right_side = A + (B + C)

# Print results

print("Left Side (A + B) + C:\n", left_side)

print("Right Side A + (B + C):\n", right_side)

# Check if they are equal

print("Are they equal? :", np.array_equal(left_side, right_side))

2. Using python find the eigenvalues and corresponding eigenvectors of the matrix
" #
3 −2
.
6 −4
-> # Define the matrix
matrix = np.array([[3, -2], [1, 1]])

# Calculate eigenvalues and eigenvectors


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

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

3. Generate all prime numbers between 1000 to 2000 using Python program.

-> def is_prime(n):


MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune
if n <= 1:

return False

for i in range(2, int(n**0.5) + 1):

if n % i == 0:

return False

return True

# Generate prime numbers between 1000 and 2000

primes = [n for n in range(1000, 2001) if is_prime(n)]

print("Prime numbers between 1000 and 2000:", primes)

Q.3. a. Attempt any one of the following. [7]


∫6 x
1. Write Python program to estimate the value of the integral 0 e dx using Simpson’s
( 1 )rd rule (n=6).

from scipy.integrate import simpson − −


import numpy as np

# Define the function to integrate


def integrand(x):
return 6 * np.exp(x)

# Generate x values and corresponding y values


x_values = np.linspace(0, 1, 5) # n = 4 (4 intervals)
y_values = integrand(x_values)

# Estimate the integral using Simpson's rule


integral_value = simpson(y_values, x_values)
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune
3
print("Estimated value of the integral ∫ 6 e^x dx from 0 to 1 using Simpson's rule:",
integral_value)
2. Write Python program to estimate a root of an equation f (x) = 3x cos(x) 1
using Newton–Raphson method correct up to four decimal places.
-> import numpy as np

# Define the function and its derivative


def f(x):
return 3 * x * np.cos(x) - 1

def f_prime(x):
return 3 * (np.cos(x) - x * np.sin(x))

# Newton-Raphson method implementation


def newton_raphson(initial_guess, tol, max_iter):
x = initial_guess
for _ in range(max_iter):
x_new = x - f(x) / f_prime(x)
if abs(x_new - x) < tol:
return round(x_new, 4)
x = x_new
return None

# Parameters for Newton-Raphson method


initial_guess = 1.0 # Initial guess
tolerance = 1e-4
max_iterations = 100

# Find the root


root = newton_raphson(initial_guess, tolerance, max_iterations)
if root is not None:
print("Approximate root of the equation 3x cos(x) - 1 = 0:", root)
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune

b. Attempt any one of the following. [8]

1. Write Python program to obtained the approximate real root of x3 − 4x − 9 = 0 by


using Regula-falsi method.

→ def regula_falsi(a, b, tol, max_iter):

if f(a) * f(b) >= 0:

print("No root found in the given interval.")

return None

for _ in range(max_iter):

c = b - (f(b) * (a - b)) / (f(a) - f(b))

if abs(f(c)) < tol:

return c

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

b=c

else:

a=c

return c

# Define the interval and parameters for Regula-Falsi method

a_rf = 2 # Lower bound

b_rf = 3 # Upper bound

tolerance_rf = 1e-4

max_iterations_rf = 100

# Find the root using Regula-Falsi method

root_rf = regula_falsi(a_rf, b_rf, tolerance_rf, max_iterations_rf)


MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune
if root_rf is not None:

print("Approximate real root of x^3 - 4x - 9 = 0:", root_rf)

2. Write Python program to evaluate interpolate value f(2.2) of the given data
f(2)=0.593,f(2.5)=0.816,f(3)=1.078.

→ # Given data points

x_values = np.array([2, 2.5, 3])

y_values = np.array([0.593, 0.816, 1.078])

# Use linear interpolation to find f(2.2)

f_2_2 = np.interp(2.2, x_values, y_values)

print("Interpolated value f(2.2):", f_2_2)


MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune

Savitribai Phule Pune University, Pune


Board of Studies in Mathematics
S.Y.B.Sc. (Computer Science)
Mathematics Practical Examination
MTC-233: Python Programming Language-I
(CBCS 2019 Pattern)(Semester-III )
Slip No.:-16

Time: 3 hour Maximum Marks: 35


Q.1. Attempt any two of the following. [10]
1. Write Python program to find absolute value of a given real number(n).
-> # Function to find the absolute value
def absolute_value(n):
return abs(n)

# Example usage
number = -42.5
print("Absolute value of", number, "is", absolute_value(number))

2. Using Python program


List1 = [5, 10, 15, 20, 25, 30] and List2 = [7, 14, 21, 28, 35, 42]
Evaluate

(a) List1 + List2


(b) 7*List1
(c) 11*List2
-> List1 = [5, 10, 15, 20, 25, 30]
List2 = [7, 14, 21, 28, 35, 42]

# (a) List1 + List2


result_sum = List1 + List2
print("List1 + List2:", result_sum)

# (b) 7 * List1
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune
result_multiply_7 = 7 * List1
print("7 * List1:", result_multiply_7)

# (c) 11 * List2
result_multiply_11 = 11 * List2
print("11 * List2:", result_multiply_11)

3. Write Python program to find the area and circumference of a circle(r=5).

-> import math

# Given radius

radius = 5

# Calculate area and circumference

area = math.pi * radius ** 2

circumference = 2 * math.pi * radius

# Print results

print("Area of the circle:", area)

print("Circumference of the circle:", circumference)

Q.2. Attempt any two of the following. [10]

1. Using Python code, find percentage of marks 70,80, 55, 78, 65 in five subject out of
100 each.

-> # Marks in five subjects

marks = [70, 80, 55, 78, 65]

total_subjects = len(marks)

total_marks = total_subjects * 100

# Calculate percentage
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune
percentage = sum(marks) / total_marks * 100

print("Percentage of marks in five subjects:", percentage)

2. Using sympy module of python, find the following terms of vector x = [1, -5, 0] and
y = [2, 3, -1].

a. 5x
b. x+y
c. x-3y
-> import numpy as np

# Define vectors
x = np.array([1, -5, 0])
y = np.array([2, 3, -1])

# (a) 5x
result_5x = 5 * x
print("5x:", result_5x)

# (b) x + y
result_add = x + y
print("x + y:", result_add)

# (c) x - 3y
result_subtract = x - 3 * y
print("x - 3y:", result_subtract)

3. Write python code to find the determinant and inverse of matrices

1 0 5 " #
2 5
A = 2 1 6 and B =
−1 4→
3 4 0
->
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune

import numpy as np

# Define matrices A and B


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

# Calculate determinant and inverse of A


det_A = np.linalg.det(A)
inv_A = np.linalg.inv(A)

# Calculate determinant and inverse of B


det_B = np.linalg.det(B)
inv_B = np.linalg.inv(B)

# Print results
print("Determinant of A:", det_A)
print("Inverse of A:\n", inv_A)
print("Determinant of B:", det_B)
print("Inverse of B:\n", inv_B)
Q.3. a. Attempt any one of the following. [7]
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune

∫π
1. Write Python program to estimate the value of the integral 0 sin(x)dx using Simp-
son’s ( 1 )rd rule (n=6).
->

import numpy as np
from scipy.integrate import simpson

# Define the function to integrate


def integrand(x):
return np.pi * np.sin(x)

# Generate x values and corresponding y values


x_values = np.linspace(0, np.pi, 5) # n = 4 (4 intervals)
y_values = integrand(x_values)

# Estimate the integral using Simpson's rule


integral_value = simpson(y_values, x_values)
3
print("Estimated value of the integral ∫ π sin(x) dx from 0 to π using Simpson's rule:",
integral_value)
2. Write Python program to estimate a root of an equation f (x) = x5 + 5x + 1 using
Newton–Raphson method in the interval [-1,0].
-> def f(x):
return x**5 + 5*x + 1

def f_prime(x):
return 5*x**4 + 5

def newton_raphson(initial_guess, tol, max_iter):


x = initial_guess
for _ in range(max_iter):
x_new = x - f(x) / f_prime(x)
if abs(x_new - x) < tol:
return round(x_new, 4)
x = x_new
return None

# Parameters for Newton-Raphson method


initial_guess = -0.5
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune
tolerance = 1e-4
max_iterations = 100

# Find the root


root = newton_raphson(initial_guess, tolerance, max_iterations)
if root is not None:
print("Approximate root of the equation x^5 + 5x + 1 = 0:", root)

b. Attempt any one of the following. [8]

1. Write Python program to obtained the approximate real root of x2 − 2x − 1 = 0 by


using Regula-falsi method in the interval [2,3].

-> def regula_falsi(a, b, tol, max_iter):

if f(a) * f(b) >= 0:

print("No root found in the given interval.")

return None

for _ in range(max_iter):

c = b - (f(b) * (a - b)) / (f(a) - f(b))

if abs(f(c)) < tol:

return c

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

b=c

else:

a=c

return c

# Define the function for Regula-Falsi

def f_regula(x):
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune
return x**2 - 2*x - 1

# Define the interval and parameters for Regula-Falsi method

a_rf = 2 # Lower bound

b_rf = 3 # Upper bound

tolerance_rf = 1e-4

max_iterations_rf = 100

# Find the root using Regula-Falsi method

root_rf = regula_falsi(a_rf, b_rf, tolerance_rf, max_iterations_rf)

if root_rf is not None:

print("Approximate real root of x^2 - 2x - 1 = 0:", root_rf)


∫ 10 1
2. Write Python program to estimate the value of the integral 2 (1+x)dx using Trape-
zoidal rule (n=8).
-> def trapezoidal_rule(a, b, n):
h = (b - a) / n
integral = 0.5 * (f_regula(a) + f_regula(b))

for i in range(1, n):


integral += f_regula(a + i * h)

integral *= h
return integral

# Define limits and number of subintervals


a_trap = 1
b_trap = 10
n_trap = 100 # Number of subintervals

# Estimate the integral using the trapezoidal rule


integral_value_trap = trapezoidal_rule(a_trap, b_trap, n_trap)
print("Estimated value of the integral ∫ from 1 to 10 dx using the trapezoidal rule:",
integral_value_trap)
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune

Savitribai Phule Pune University, Pune


Board of Studies in Mathematics
S.Y.B.Sc. (Computer Science)
Mathematics Practical Examination
MTC-233: Python Programming Language-I
(CBCS 2019 Pattern)(Semester-III )
Slip No.:-17

Time: 3 hour Maximum Marks: 35


Q.1. Attempt any two of the following. [10]
1. Write the Python code to print ‘Python is bad’ and ‘Python is wonderful’ , where
wonderful is global variable and bad is local variable.

-> # Global variable

wonderful = "wonderful"

def print_messages():

# Local variable

bad = "bad"

print(f"Python is {bad}")

print(f"Python is {wonderful}")

# Call the function

print_messages()

2. Write Python code to evaluate eigen value and eigen vector of the following matrix.

1 1 1
A = 0 1 1
0 0 1

-> import numpy as np


MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune

# Define the matrix A


A = np.array([[1, 1, 1],
[0, 1, 1],
[0, 0, 1]])

# Calculate eigenvalues and eigenvectors


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

# Print results
print("Eigenvalues:", eigenvalues)
print("Eigenvectors:\n", eigenvectors)
3. Write Python code, find a, b and c such that a2 + b2 = c2.(where 1 ≤ a, b, c ≤ 50)
-># Find Pythagorean triples
triples = []

for a in range(1, 51):


for b in range(a, 51): # Start from a to avoid duplicates
for c in range(b, 51): # Start from b to avoid duplicates
if a**2 + b**2 == c**2:
triples.append((a, b, c))

# Print the results


print("Pythagorean triples (a, b, c) where 1 ≤ a, b, c ≤ 50:")
for triple in triples:
print(triple)

Q.2. Attempt any two of the following. [10]

1. Using Python code construct any two matrices A and B to show that
(AB)−1 = B−1A−1.

->import numpy as np

# Define matrices A and B

A = np.array([[1, 2],

[3, 4]])

B = np.array([[2, 0],

[1, 2]])
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune

# Calculate the product AB

AB = np.dot(A, B)

# Calculate the inverses

AB_inv = np.linalg.inv(AB)

B_inv_A_inv = np.dot(np.linalg.inv(B), np.linalg.inv(A))

# Print results

print("Inverse of AB:\n", AB_inv)

print("B^(-1) * A^(-1):\n", B_inv_A_inv)

# Check if they are equal

print("Are they equal?", np.allclose(AB_inv, B_inv_A_inv))

2. Use linsolve code in python to solve the following system of linear equations.

x − 2y + 3z = 7
2x + y + z = 4
−3x + 2y − 2z = −10

from sympy import symbols, Eq, linsolve

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

# Define equations
eq1 = Eq(x - 2*y + 3*z, 7)
eq2 = Eq(2*x + y + z, 4)
eq3 = Eq(-3*x + 2*y - 2*z, -10)

# Solve the system of equations


solution = linsolve((eq1, eq2, eq3), (x, y, z))
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune
print("Solution of the system of equations:", solution)
1 3 3
3. Write python code to find trace and transpose of the matrix 2 2 3
4 2 1

# Define the matrix


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

# Calculate trace and transpose


matrix_trace = np.trace(matrix)
matrix_transpose = np.transpose(matrix)

# Print results
print("Trace of the matrix:", matrix_trace)
print("Transpose of the matrix:\n", matrix_transpose)

Q.3. a. Attempt any one of the following. [7]

1. Write Python program to find f(3) of the functional value f(1)=2, f(2)=10, f(4)=68by
using Lagrange method.

-># Lagrange interpolation function


def lagrange_interpolation(x_values, y_values, x):
total = 0
n = len(x_values)

for i in range(n):
term = y_values[i]
for j in range(n):
if j != i:
term *= (x - x_values[j]) / (x_values[i] - x_values[j])
total += term
return total

# Given data points


x_values = [1, 2, 4]
y_values = [2, 10, 68]
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune
# Estimate f(3)
f_3 = lagrange_interpolation(x_values, y_values, 3)
print("f(3) using Lagrange interpolation:", f_3)
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune

2. Write Python program to estimate a root of an equation x5 − 5x + 6 = 0 using


Newton–Raphson method correct up to four decimal places.
->def f_newton(x):
return x**5 + 5*x + 6

def f_prime_newton(x):
return 5*x**4 + 5

def newton_raphson_newton(initial_guess, tol, max_iter):


x = initial_guess
for _ in range(max_iter):
x_new = x - f_newton(x) / f_prime_newton(x)
if abs(x_new - x) < tol:
return round(x_new, 4)
x = x_new
return None

# Parameters for Newton-Raphson method


initial_guess_newton = -1 # Initial guess
tolerance_newton = 1e-4
max_iterations_newton = 100

# Find the root


root_newton = newton_raphson_newton(initial_guess_newton, tolerance_newton,
max_iterations_newton)
if root_newton is not None:
print("Approximate root of the equation x^5 + 5x + 6 = 0:", root_newton)

b. Attempt any one of the following. [8]

1. Write Python program to obtained the approximate real root of x2 − 2x − 1 = 0 by


using Regula-falsi method in the interval [1,3].

->def regula_falsi_method(a, b, tol, max_iter):


MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune
if f_newton(a) * f_newton(b) >= 0:

print("No root found in the given interval.")

return None

for _ in range(max_iter):

c = b - (f_newton(b) * (a - b)) / (f_newton(a) - f_newton(b))

if abs(f_newton(c)) < tol:

return c

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

b=c

else:

a=c

return c

# Define the interval and parameters for Regula-Falsi method

a_rf = 1 # Lower bound

b_rf = 3 # Upper bound

tolerance_rf = 1e-4

max_iterations_rf = 100

# Find the root using Regula-Falsi method

root_rf = regula_falsi_method(a_rf, b_rf, tolerance_rf, max_iterations_rf)

if root_rf is not None:

print("Approximate real root of x^2 - 2x - 1 = 0:", root_rf)


∫1
2. Write Python program to estimate the value of the integral x2dx using Trape-
0
zoidal rule (n=10).
->def f_trap(x):
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune
return x**2

def trapezoidal_rule_trap(a, b, n):


h = (b - a) / n
integral = 0.5 * (f_trap(a) + f_trap(b))

for i in range(1, n):


integral += f_trap(a + i * h)

integral *= h
return integral

# Define limits and number of subintervals


a_trap = 0
b_trap = 1
n_trap = 10 # Number of subintervals

# Estimate the integral using the trapezoidal rule


integral_value_trap = trapezoidal_rule_trap(a_trap, b_trap, n_trap)
print("Estimated value of the integral ∫ x^2 dx from 0 to 1 using the trapezoidal
rule:", integral_value_trap)
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune

Savitribai Phule Pune University, Pune


Board of Studies in Mathematics
S.Y.B.Sc. (Computer Science)
Mathematics Practical Examination
MTC-233: Python Programming Language-I
(CBCS 2019 Pattern)(Semester-III )
Slip No.:-18

Time: 3 hour Maximum Marks: 35


Q.1. Attempt any two of the following. [10]
1. Use Python code to find minimum value from the given numbers
16,3,5,48,2,4,5,6,78,12,5,6,24.
-> # Given numbers
numbers = [16, 3, 5, 48, 2, 4, 5, 6, 78, 12, 5, 6, 24]

# Find the minimum value


min_value = min(numbers)
print("Minimum value from the given numbers:", min_value)

2. Use Python code to find hypotenuse of triangle whose sides are 12 and 5.
-> import math

# Given sides
side_a = 12
side_b = 5

# Calculate the hypotenuse using Pythagorean theorem


hypotenuse = math.sqrt(side_a**2 + side_b**2)
print("Hypotenuse of the triangle:", hypotenuse)

3. Use Python code to remove all digits after decimal of the given Number 125312.3142.
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune
-> # Given number

number = 125312.3142

# Remove digits after decimal

number_without_decimal = int(number)

print("Number without decimal:", number_without_decimal)

Q.2. Attempt any two of the following. " # " # [10]


2 4 4 3
1. Using Python code, find the below matrices, where A = and B =
4 3 5 4

(a) A+B
(b) AT
(c) A−1
-> import numpy as np

# Define matrices A and B


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

B = np.array([[4, 3],
[5, 4]])

# (a) A + B
matrix_sum = A + B

# (b) A^T (transpose of A)


A_transpose = A.T

# (c) A^(-1) (inverse of A)


A_inverse = np.linalg.inv(A)

# Print results
print("A + B:\n", matrix_sum)
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune
print("Transpose of A:\n", A_transpose)
print("Inverse of A:\n", A_inverse)

2. Use while code on Python to find sum of first twenty natural number.

-> # Initialize variables

n=1

sum_natural_numbers = 0

# Calculate the sum using a while loop

while n <= 20:

sum_natural_numbers += n

n += 1

print("Sum of the first twenty natural numbers:", sum_natural_numbers)

3. Write Python program to diagonalize the matrix

"
3 2#
−6 −4

and find matrix P and D.


-> from scipy.linalg import eig

# Define the matrix


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

# Calculate eigenvalues and eigenvectors


eigenvalues, eigenvectors = eig(matrix)

# Diagonal matrix D
D = np.diag(eigenvalues)
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune

# Matrix P (eigenvectors)
P = eigenvectors

# Print results
print("Diagonal matrix D:\n", D)
print("Matrix P (eigenvectors):\n", P)

Q.3. a. Attempt any one of the following. [7]


∫31
1. Write Python program to estimate the value of the integral 1 xdx using Simpson’s
( 1 )rd rule (n=8).
3
-> def simpsons_rule(a, b, n):
if n % 2 == 1:
raise ValueError("n must be an even number")

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

for i in range(1, n):


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

integral *= h / 3
return integral

# Function to integrate
def f(x):
return 1 # The integral of dx is simply 1

# Parameters
a=1
b=3
n = 4 # Even number

# Estimate the integral using Simpson's rule


integral_value = simpsons_rule(a, b, n)
print("Estimated value of the integral ∫_1^3 dx using Simpson's rule:", integral_value)
2. Write Python program to evaluate interpolate value f (2.9) of the given data.
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune
-> # Given data
x_data = [1, 2, 3, 4]
y_data = [11, 9, 27, 64]

def lagrange_interpolation(x_values, y_values, x):


total = 0
n = len(x_values)

for i in range(n):
term = y_values[i]
for j in range(n):
if j != i:
term *= (x - x_values[j]) / (x_values[i] - x_values[j])
total += term
return total

# Estimate f(2.9)
f_2_9 = lagrange_interpolation(x_data, y_data, 2.9)
print("Interpolated value f(2.9):", f_2_9)
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune

x 1 2 3 4
Y=f(x) 11 9 27 64

b. Attempt any one of the following. [8]

1. Write Python program to obtained the approximate real root of x3 − 5x − 9 = 0 in


[2,3] using Regula-falsi method.

-> def f_rf(x):

return x**3 + 5*x - 9

def regula_falsi(a, b, tol, max_iter):

if f_rf(a) * f_rf(b) >= 0:

print("No root found in the given interval.")

return None

for _ in range(max_iter):

c = b - (f_rf(b) * (a - b)) / (f_rf(a) - f_rf(b))

if abs(f_rf(c)) < tol:

return c

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

b=c

else:

a=c

return c

# Parameters for Regula-Falsi method

a_rf = 2 # Lower bound

b_rf = 3 # Upper bound


MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune
tolerance_rf = 1e-4

max_iterations_rf = 100

# Find the root using Regula-Falsi method

root_rf = regula_falsi(a_rf, b_rf, tolerance_rf, max_iterations_rf)

if root_rf is not None:

print("Approximate real root of x^3 + 5x - 9 = 0:", root_rf)


∫1
2. Write Python program to estimate the value of the integral cos(x)dx using Trape-
0
zoidal rule (n=5).
-> import numpy as np

def f_trap_cos(x):
return np.cos(x)

def trapezoidal_rule_cos(a, b, n):


h = (b - a) / n
integral = 0.5 * (f_trap_cos(a) + f_trap_cos(b))

for i in range(1, n):


integral += f_trap_cos(a + i * h)

integral *= h
return integral

# Define limits and number of subintervals


a_trap_cos = 1
b_trap_cos = np.pi / 2 # Upper limit to estimate ∫_1^π/2 cos(x) dx
n_trap_cos = 5 # Number of subintervals

# Estimate the integral using the trapezoidal rule


integral_value_trap_cos = trapezoidal_rule_cos(a_trap_cos, b_trap_cos,
n_trap_cos)
print("Estimated value of the integral ∫_1^π/2 cos(x) dx using the trapezoidal
rule:", integral_value_trap_cos)
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune

Savitribai Phule Pune University, Pune


Board of Studies in Mathematics
S.Y.B.Sc. (Computer Science)
Mathematics Practical Examination
MTC-233: Python Programming Language-I
(CBCS 2019 Pattern)(Semester-III )
Slip No.:-19

Time: 3 hour Maximum Marks: 35


Q.1. Attempt any two of the following. [10]
1. Write python code to display multiplication tables of numbers 2 to 10.
-> # Display multiplication tables for numbers 2 to 10
for i in range(2, 11):
print(f"Multiplication Table for {i}:")
for j in range(1, 11):
print(f"{i} x {j} = {i * j}")
print() # Blank line for better readability

2. Write Python code to check if a number is Zero, Odd or Even.

-> # Function to check if a number is Zero, Odd, or Even

def check_number(num):

if num == 0:

return "The number is Zero."

elif num % 2 == 0:

return "The number is Even."

else:

return "The number is Odd."

# Test the function


MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune
number = int(input("Enter a number: "))

result = check_number(number)

print(result)

3. Write Python code to list name and birth date of 5 students in your class.

-> # List of students with names and birth dates

students = [

{"name": "Alice", "birth_date": "2000-01-15"},

{"name": "Bob", "birth_date": "1999-04-20"},

{"name": "Charlie", "birth_date": "2001-07-10"},

{"name": "David", "birth_date": "2000-09-30"},

{"name": "Eva", "birth_date": "2002-12-05"},

# Display the name and birth date of each student

print("List of Students:")

for student in students:

print(f"Name: {student['name']}, Birth Date: {student['birth_date']}")

Q.2. Attempt any two of the following. [10]

1. Write python code to find transpose and inverse of matrix

1 2 2
A= 2 1 2
2 2 1
-> import numpy as np

# Define the matrix A


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

# Calculate the transpose of A


MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune
A_transpose = A.T

# Calculate the inverse of A


A_inverse = np.linalg.inv(A)

# Print results
print("Matrix A:\n", A)
print("Transpose of A:\n", A_transpose)
print("Inverse of A:\n", A_inverse)

2.Declare the matrix

5 2 5 4
A = 10 3 4 6
2 0 −1 11

find a row echelon form and the rank of matrix A.


-> from scipy.linalg import lu

# Define the matrix A


A = np.array([[5, 2, 5, 4],
[10, 3, 4, 6],
[2, 0, -1, 11]])

# Get the row echelon form and rank of A


P, L, U = lu(A) # LU decomposition

# Rank of the matrix


rank_A = np.linalg.matrix_rank(A)

# Print results
print("Matrix A:\n", A)
print("Row Echelon Form (Upper Triangular Matrix U):\n", U)
print("Rank of Matrix A:", rank_A)

2. Declare the matrix


MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune

2 −1 2 7
A= 4 7 3 4
4 2 0 −1

find the matrices L and U such that A = LU .

-> from scipy.linalg import lu

# Define the matrix A

A = np.array([[2, -1, 2, 7],

[4, 2, 0, -1]])

# LU decomposition

P, L, U = lu(A)

# Print results

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

print("Lower Triangular Matrix L:\n", L)

print("Upper Triangular Matrix U:\n", U)

Q.3. a. Attempt any one of the following. [7]


MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune
∫1
1. Write Python program to estimate the value of the integral 1
2 dx by using

Simpson’s ( 83 )th rule (n=6). print("Estimated


value of the integral
-> def f(x):
∫_0^1 (1 + 2x) dx
return 1 + 2 * x # using Simpson's
Function to integrate rule:",
integral_value)

def simpsons_rule(a, b, n):


if n % 2 != 0:
raise ValueError("n
must be an even number.")

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

for i in range(1, n):


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

integral *= h / 3
return integral

# Parameters
a=0
b=1
n = 6 # Even number

# Estimate the integral


using Simpson's rule
integral_value =
simpsons_rule(a, b, n)
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune

0 1+x

2. Write Python program to obtained the approximate real root of x3 − 8x − 4 = 0


using Regula-falsi method.

-> def f_rf(x):

return x**3 - 8*x + 4 # Function whose root we need to find

def regula_falsi(a, b, tol, max_iter):

if f_rf(a) * f_rf(b) >= 0:

print("No root found in the given interval.")

return None

for _ in range(max_iter):

c = b - (f_rf(b) * (a - b)) / (f_rf(a) - f_rf(b))

if abs(f_rf(c)) < tol:

return c

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

b=c

else:

a=c

return c

# Parameters for Regula-Falsi method

a_rf = 1 # Lower bound

b_rf = 3 # Upper bound

tolerance_rf = 1e-4

max_iterations_rf = 100
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune

# Find the root using Regula-Falsi method

root_rf = regula_falsi(a_rf, b_rf, tolerance_rf, max_iterations_rf)

if root_rf is not None:

print("Approximate real root of x^3 - 8x + 4 = 0:", root_rf)

b. Attempt any one of the following. [8]


∫1
1. Write Python program to estimate the value of the integral x2dx using Trape-
0
zoidal rule (n=5).
-> def f_trap(x):
return x**2 # Function to integrate

def trapezoidal_rule(a, b, n):


h = (b - a) / n
integral = 0.5 * (f_trap(a) + f_trap(b))

for i in range(1, n):


integral += f_trap(a + i * h)

integral *= h
return integral

# Define limits and number of subintervals


a_trap = 1
b_trap = 1 # Upper limit
n_trap = 5 # Number of subintervals

# Estimate the integral using the trapezoidal rule


integral_value_trap = trapezoidal_rule(a_trap, b_trap, n_trap)
print("Estimated value of the integral ∫_1^1 x^2 dx using the trapezoidal rule:",
integral_value_trap)

2. Write python program to find sin(42)0 using Newton backward interpolation for-
mula for the data:
sin300 = 0.5, sin350 = 0.5736, sin400 = 0.6428, sin450 = 0.7071.
-> # Given data for interpolation
x_data = [30, 35, 40, 45]
y_data = [0.5, 0.5736, 0.6428, 0.7071]
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune

# Newton backward interpolation


def backward_interpolation(x, x_data, y_data):
n = len(y_data)
diff_table = np.zeros((n, n))
diff_table[:, 0] = y_data

# Calculate the backward difference table


for j in range(1, n):
for i in range(n - j):
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune

Savitribai Phule Pune University, Pune


Board of Studies in Mathematics
S.Y.B.Sc. (Computer Science)
Mathematics Practical Examination
MTC-233: Python Programming Language-I
(CBCS 2019 Pattern)(Semester-III )
Slip No.:-20

Time: 3 hour Maximum Marks: 35


Q.1. Attempt any two of the following. [10]
1. Write Python code to print first n natural numbers and their square roots of input
integer n.
-> import math

# Function to print first n natural numbers and their square roots


def print_natural_numbers_and_squares(n):
print(f"First {n} natural numbers and their square roots:")
for i in range(1, n + 1):
print(f"Number: {i}, Square Root: {math.sqrt(i):.2f}")

# Input from user


n = int(input("Enter an integer n: "))
print_natural_numbers_and_squares(n)

2. Use Python code to find sum of square of first twenty five natural numbers.

-> # Function to find the sum of squares of the first n natural numbers

def sum_of_squares(n):

return sum(i**2 for i in range(1, n + 1))

# Calculate sum of squares for the first 25 natural numbers


MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune
n = 25

result = sum_of_squares(n)

print(f"The sum of squares of the first {n} natural numbers is: {result}")

3. Write Python code to find all positive divisors of given number n.

-> # Function to find all positive divisors of a given number n

def positive_divisors(n):

divisors = [i for i in range(1, n + 1) if n % i == 0]

return divisors

# Input from user

n = int(input("Enter a number to find its positive divisors: "))

divisors = positive_divisors(n)

print(f"The positive divisors of {n} are: {divisors}")

Q.2. Attempt any two of the following. [10]

1. Write python code to display tuple ‘I am Indian ’ and the second letter in this tuple

-> # Define the tuple

my_tuple = ("I", "am", "Indian")

# Display the tuple and the second letter

print("Tuple:", my_tuple)

print("Second letter in the tuple:", my_tuple[1][1]) # Accessing second letter in "am"

2. Write python code to display the matrix whose all entries are 10 and order is (4,6).

-> import numpy as np

# Create a matrix of order (4, 6) with all entries as 10

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


MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune

# Display the matrix

print("Matrix of order (4, 6) with all entries as 10:")

print(matrix)

3. Write Python program to diagonalize the matrix

"
3 2#
−6 −4

and find matrix P and D.


-> from scipy.linalg import eig

# Define the matrix A


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

# Compute eigenvalues and eigenvectors


eigenvalues, eigenvectors = eig(A)

# Diagonal matrix D
D = np.diag(eigenvalues)

# Matrix P (eigenvectors)
P = eigenvectors

# Display results
print("Matrix A:\n", A)
print("Matrix P (eigenvectors):\n", P)
print("Diagonal Matrix D (eigenvalues):\n", D)

Q.3. a. Attempt any one of the following. [7]


MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune
∫3
1. Write Python program to estimate the value of the integral 1
cos(x)dx using Simp-
son’s ( 3 )th rule (n=6).

import numpy as np

def f(x):
return np.cos(x)

def simpsons_rule(a, b, n):


if n % 2 != 0:
raise ValueError("n must be an even number.")

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

for i in range(1, n):


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

integral *= h / 3
return integral

# Parameters
a=3
b=5
n = 6 # Even number of intervals

# Estimate the integral using Simpson's rule


integral_value = simpsons_rule(a, b, n)
8
print(f"Estimated value of the integral ∫_3^5 cos(x) dx using Simpson's rule:
{integral_value}")
2. Write Python program to evaluate interpolate value f (5) of the given data.
-> import numpy as np

# Given data points


x_data = np.array([1, 2, 3, 6])
y_data = np.array([2, 6, 12, 42])
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune
# Lagrange Interpolation Function
def lagrange_interpolation(x, x_data, y_data):
total_sum = 0
n = len(x_data)

for i in range(n):
term = y_data[i]
for j in range(n):
if j != i:
term *= (x - x_data[j]) / (x_data[i] - x_data[j])
total_sum += term
return total_sum

# Interpolate for f(5)


interpolated_value = lagrange_interpolation(5, x_data, y_data)
print(f"Interpolated value f(5): {interpolated_value}")

x 1 2 3 6
Y=f(x) 2 6 12 42

b. Attempt any one of the following. [8]


MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune

1. Write Python program to obtained the approximate real root of x3 − 5x − 9 = 0 in


[2,3] using Regula-falsi method.
-> def f_rf(x):
return x**3 - 5*x + 9 # Function whose root we need to find

def regula_falsi(a, b, tol, max_iter):


if f_rf(a) * f_rf(b) >= 0:
print("No root found in the given interval.")
return None

for _ in range(max_iter):
c = b - (f_rf(b) * (a - b)) / (f_rf(a) - f_rf(b))
if abs(f_rf(c)) < tol:
return c
if f_rf(c) * f_rf(a) < 0:
b=c
else:
a=c

return c

# Parameters for Regula-Falsi method


a_rf = 2 # Lower bound
b_rf = 3 # Upper bound
tolerance_rf = 1e-4
max_iterations_rf = 100

# Find the root using Regula-Falsi method


root_rf = regula_falsi(a_rf, b_rf, tolerance_rf, max_iterations_rf)
if root_rf is not None:
print("Approximate real root of x^3 - 5x + 9 = 0:", root_rf)
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune
∫5
2. Write Python program to estimate the value of the integral (x3 − 3x + 2)dx using
1
Trapezoidal rule (n=5).
-> def f_trap(x):
return 5 * (x**3 - 3*x + 2) # Function to integrate

def trapezoidal_rule(a, b, n):


h = (b - a) / n
integral = 0.5 * (f_trap(a) + f_trap(b))

for i in range(1, n):


integral += f_trap(a + i * h)

integral *= h
return integral

# Define limits and number of subintervals


a_trap = 5
b_trap = 10
n_trap = 5 # Number of subintervals

# Estimate the integral using the trapezoidal rule


integral_value_trap = trapezoidal_rule(a_trap, b_trap, n_trap)
print(f"Estimated value of the integral ∫_5^10 (x^3 - 3x + 2) dx using the
trapezoidal rule: {integral_value_trap}")
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune

Savitribai Phule Pune University, Pune


Board of Studies in Mathematics
S.Y.B.Sc. (Computer Science)
Mathematics Practical Examination
MTC-233: Python Programming Language-I
(CBCS 2019 Pattern)(Semester-III )
Slip No.:-21

Time: 3 hour Maximum Marks: 35


Q.1. Attempt any two of the following. [10]
1. Write Python code to display multiplication tables of numbers 20 to 30.
-> # Function to display multiplication tables for numbers 20 to 30
def multiplication_tables(start, end):
for i in range(start, end + 1):
print(f"\nMultiplication Table of {i}:")
for j in range(1, 11):
print(f"{i} x {j} = {i * j}")

# Display multiplication tables from 20 to 30


multiplication_tables(20, 30)

2. Write Python code to list name and birth date of 5 students in your class.

-> # List of students with their names and birth dates

students = [

{"name": "Alice", "birth_date": "2001-05-12"},

{"name": "Bob", "birth_date": "2000-11-23"},

{"name": "Charlie", "birth_date": "1999-08-30"},

{"name": "David", "birth_date": "2002-02-15"},

{"name": "Eva", "birth_date": "2000-03-10"}

]
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune

# Display the names and birth dates of students

print("Name and Birth Date of Students:")

for student in students:

print(f"Name: {student['name']}, Birth Date: {student['birth_date']}")

3. Write Python function f (a, b) = (4a+b) , find


3(a–6b)
the value of f (12, 25).

-> # Function to calculate f(a, b) = 4a + b

def f(a, b):

return 4 * a + b

# Calculate f(12, 25)

result = f(12, 25)

print(f"The value of f(12, 25) is: {result}")

Q.2. Attempt any two of the following. [10]

1. Using Python construct the following matrices.

1. Matrix of order 5×6 with all entries 1.


2. Zero matrix of order 27 × 33.
3. Identity matrix of order 5.
-> import numpy as np

# 1. Matrix of order 5x6 with all entries as 1


matrix_ones = np.ones((5, 6))
print("Matrix of order 5x6 with all entries as 1:\n", matrix_ones)

# 2. Zero matrix of order 27x33


zero_matrix = np.zeros((27, 33))
print("\nZero matrix of order 27x33:\n", zero_matrix)

# 3. Identity matrix of order 5


MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune
identity_matrix = np.eye(5)
print("\nIdentity matrix of order 5:\n", identity_matrix)

2. Write python code to perform the R2 + 2R1 row operation on given matrix.

1 1 1
R= 2 2 2
3 3 3

-> # Define the initial matrix

matrix = np.array([[1, 1, 1],

[3, 3, 3]])

# Perform the row operation R2 + 2R1

matrix[1] = matrix[1] + 2 * matrix[0]

# Display the resulting matrix

print("Matrix after performing the operation R2 + 2R1:\n", matrix)

3. Write python code to find all the eigen values and the eigen vectors of the matrix.

2 −1 −1 0
−1 3 −1 −1
−1 −1 3 −1
−1 −1 −1 2

-> # Define the matrix

A = np.array([[2, -1, -1, 0],

[-1, -1, -1, 2]])


MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune

# Calculate eigenvalues and eigenvectors

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

# Display the results

print("Eigenvalues:\n", eigenvalues)

print("\nEigenvectors:\n", eigenvectors)

Q.3. a. Attempt any one of the following. [7]

1. Write Python program to find the approximate root of the equation x5 + 3x + 1 = 0,


by using Newton Raphson method.

-> def f_newton(x):


return x**5 + 3*x + 1 # Function to find the root

def df_newton(x):
return 5*x**4 + 3 # Derivative of the function

def newton_raphson(x0, tol, max_iter):


for _ in range(max_iter):
x1 = x0 - f_newton(x0) / df_newton(x0)
if abs(x1 - x0) < tol:
return x1
x0 = x1
return None

# Parameters
x0 = -1 # Initial guess
tolerance = 1e-6
max_iterations = 100

# Find the root using the Newton-Raphson method


root = newton_raphson(x0, tolerance, max_iterations)
print("Approximate root of x^5 + 3x + 1 = 0:", root)
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune

2. Write a Python program to evaluate interpolate value f (3) of the given data.
-> # Given data points
x_data = np.array([1, 2, 3, 4])
y_data = np.array([11, 22, 33, 66])

# Lagrange Interpolation Function


def lagrange_interpolation(x, x_data, y_data):
total_sum = 0
n = len(x_data)

for i in range(n):
term = y_data[i]
for j in range(n):
if j != i:
term *= (x - x_data[j]) / (x_data[i] - x_data[j])
total_sum += term
return total_sum

# Interpolate for f(3)


interpolated_value = lagrange_interpolation(3, x_data, y_data)
print(f"Interpolated value f(3): {interpolated_value}")

x 1 2 3 4
Y=f(x) 11 22 33 66

b. Attempt any one of the following. [8]

1. Write Python program to obtained the approximate real root of xsin(x)+cos(x) = 0


by using Regula-falsi method

-> def f_regula_falsi(x):

return x * np.sin(x) + np.cos(x) # Function whose root we need to find


MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune
def regula_falsi(a, b, tol, max_iter):

if f_regula_falsi(a) * f_regula_falsi(b) >= 0:

print("No root found in the given interval.")

return None

for _ in range(max_iter):

c = b - (f_regula_falsi(b) * (a - b)) / (f_regula_falsi(a) - f_regula_falsi(b))

if abs(f_regula_falsi(c)) < tol:

return c

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

b=c

else:

a=c

return c

# Parameters for Regula-Falsi method

a_rf = 0 # Lower bound

b_rf = 1 # Upper bound

tolerance_rf = 1e-6

max_iterations_rf = 100

# Find the root using Regula-Falsi method

root_rf = regula_falsi(a_rf, b_rf, tolerance_rf, max_iterations_rf)

if root_rf is not None:

print("Approximate real root of x sin(x) + cos(x) = 0:", root_rf)

2. Write Python program to find sin(37)0 using Newton backward interpolation for-
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune
mula for the data:
sin300 = 0.5, sin350 = 0.5736, sin400 = 0.6428, sin450 = 0.7071.
-> # Given data points
x_values = np.array([30, 35, 40, 45])
y_values = np.array([0.5, 0.5736, 0.6428, 0.7071])

# Newton Backward Interpolation Function


def newton_backward_interpolation(x, x_values, y_values):
n = len(x_values)
h = x_values[1] - x_values[0] # Assuming uniform spacing
k = (x - x_values[0]) / h

# Calculate backward differences


backward_diff = np.zeros((n, n))
backward_diff[:, 0] = y_values

for j in range(1, n):


for i in range
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune

Savitribai Phule Pune University, Pune


Board of Studies in Mathematics
S.Y.B.Sc. (Computer Science)
Mathematics Practical Examination
MTC-233: Python Programming Language-I
(CBCS 2019 Pattern)(Semester-III )
Slip No.:-22

Time: 3 hour Maximum Marks: 35


Q.1. Attempt any two of the following. [10]
1. Write Python code to sort a tuples in ascending order (49, 17, 23, 54, 36, 72).
-> # Tuple to be sorted
numbers = (49, 17, 23, 54, 36, 72)

# Sorting the tuple


sorted_numbers = tuple(sorted(numbers))

# Display the sorted tuple


print("Sorted tuple in ascending order:", sorted_numbers)
2. Find the values of the following expressions if x and y are true and z is false.

(a) (x or y) and z.
(b) (x and y) or not z.
(c) (x and not y) or (x and z).
-> # Given boolean values
x = True
y = True
z = False

# Calculate the expressions


expression_a = (x or y) and z
expression_b = (x and y) or not z
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune
expression_c = (x and not y) or (x and z)

# Display the results


print("Expression (a) (x or y) and z:", expression_a)
print("Expression (b) (x and y) or not z:", expression_b)
print("Expression (c) (x and not y) or (x and z):", expression_c)

3. Write Python code to find the tuple ‘MATHEMATICS’ from range 3 to 9.

-> # String to extract substring from

string = 'MATHEMATICS'

# Extracting substring from index 3 to 9

substring = string[3:9]

# Display the extracted substring

print("Substring from range 3 to 9:", substring)

Q.2. Attempt any two of the following. [10]

1. Write Python program that prints whether the given number is positive, negative
or zero.

-> # Function to check if a number is positive, negative, or zero

def check_number(num):

if num > 0:

return "Positive"

elif num < 0:

return "Negative"

else:

return "Zero"
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune
# Input number

number = float(input("Enter a number: "))

result = check_number(number)

print(f"The number is: {result}")

2. Write Python program to find the sum of first n natural numbers.


-> # Function to find the sum of first n natural numbers
def sum_of_natural_numbers(n):
return n * (n + 1) // 2 # Using the formula n(n + 1)/2

# Input value of n
n = int(input("Enter the value of n: "))
sum_n = sum_of_natural_numbers(n)
print(f"The sum of first {n} natural numbers is: {sum_n}")

3. Using Python accept the matrix

1 −3 2 −4
− 3 9 −1 5
A=
5 −2 6 −3
−4 12 2 7

Find the Null space, Column space and rank of the matrix.

-> import numpy as np

# Accepting the matrix input

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

[3, 9, 1, 5],

[-4, 12, 2, 7]])


MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune
# Finding the rank of the matrix

rank = np.linalg.matrix_rank(matrix)

# Finding the null space using SVD

u, s, vh = np.linalg.svd(matrix)

null_space_dimension = matrix.shape[1] - rank

null_space = vh.T[:, null_space_dimension:]

# Finding the column space (the span of the matrix columns)

column_space = matrix[:, :rank] # Columns corresponding to the rank

# Display results

print("Null Space:\n", null_space)

print("Column Space:\n", column_space)

print("Rank of the matrix:", rank)

Q.3. a. Attempt any one of the following. [7]

1. Write Python program to find the approximate root of f (x) = x3 − 10x2 + 5 = 0,


using Newton Raphson method. Take x0 = 0.5.

-> def f_newton_raphson(x):

return x**3 + 10*x**2 + 5 # Function

def df_newton_raphson(x):

return 3*x**2 + 20*x # Derivative


MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune
def newton_raphson(x0, tol, max_iter):

for _ in range(max_iter):

x1 = x0 - f_newton_raphson(x0) / df_newton_raphson(x0)

if abs(x1 - x0) < tol:

return x1

x0 = x1

return None

# Parameters

x0 = 0.5 # Initial guess

tolerance = 1e-6

max_iterations = 100

# Find the root using Newton-Raphson method

root_nr = newton_raphson(x0, tolerance, max_iterations)

print("Approximate root of f(x) = x^3 + 10x^2 + 5 = 0:", root_nr)

2. Write Python program to evaluate interpolate value f (2) of the given data.

-> # Given data points


x_data = np.array([11, 12, 13, 14])
y_data = np.array([21, 19, 27, 64])

# Lagrange Interpolation Function


def lagrange_interpolation(x, x_data, y_data):
total_sum = 0
n = len(x_data)

for i in range(n):
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune
term = y_data[i]
for j in range(n):
if j != i:
term *= (x - x_data[j]) / (x_data[i] - x_data[j])
total_sum += term
return total_sum

# Interpolate for f(2)


interpolated_value = lagrange_interpolation(2, x_data, y_data)
print(f"Interpolated value f(2): {interpolated_value}")
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune

x 11 12 13 14
Y=f(x) 21 19 27 64

b. Attempt any one of the following. [8]

1. Write Python program to obtained the approximate real root of x3 − x2 − 2 = 0 in


[1,2], using Regula-falsi method.

-> def f_regula_falsi(x):

return x**3 - x**2 - 2 # Function

def regula_falsi(a, b, tol, max_iter):

if f_regula_falsi(a) * f_regula_falsi(b) >= 0:

print("No root found in the given interval.")

return None

for _ in range(max_iter):

c = b - (f_regula_falsi(b) * (a - b)) / (f_regula_falsi(a) - f_regula_falsi(b))

if abs(f_regula_falsi(c)) < tol:

return c

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

b=c

else:

a=c

return c

# Parameters

a_rf = 1 # Lower bound

b_rf = 2 # Upper bound


MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune
tolerance_rf = 1e-6

max_iterations_rf = 100

# Find the root using Regula-Falsi method

root_rf = regula_falsi(a_rf, b_rf, tolerance_rf, max_iterations_rf)

if root_rf is not None:

print("Approximate real root of x^3 - x^2 - 2 = 0:", root_rf)

2. Using python accept the matrix

1 2 3
A= 2 5 3
1 0 8

Find the transpose of the matrix, determinant, inverse of the matrix. Also reduce
the matrix to reduced row echelon form and diagonalize it.

-> # Accepting the matrix input

matrix = np.array([[1, 2, 3],

[1, 0, 8]])

# Transpose of the matrix

transpose_matrix = np.transpose(matrix)

# Determinant of the matrix

determinant = np.linalg.det(matrix)

# Inverse of the matrix (if it exists)

try:
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune
inverse_matrix = np.linalg.inv(matrix)

except np.linalg.LinAlgError:

inverse_matrix = None

# Reduced Row Echelon Form using sympy

import sympy as sp

# Create a sympy matrix for row echelon form

sympy_matrix = sp.Matrix(matrix)

rref_matrix, _ = sympy_matrix.rref()

# Diagonalization (if possible)

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

# Display results

print("Transpose of the matrix:\n", transpose_matrix)

print("Determinant of the matrix:", determinant)

print("Inverse of the matrix:\n", inverse_matrix)

print("Reduced Row Echelon Form:\n", rref_matrix)

print("Eigenvalues:\n", eigenvalues)

print("Eigenvectors:\n", eigenvectors)
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune

Savitribai Phule Pune University, Pune


Board of Studies in Mathematics
S.Y.B.Sc. (Computer Science)
Mathematics Practical Examination
MTC-233: Python Programming Language-I
(CBCS 2019 Pattern)(Semester-III )
Slip No.:-23

Time: 3 hour Maximum Marks: 35


Q.1. Attempt any two of the following. [10]
1. Write Python program to find the sum of first n natural numbers.
-> # Function to calculate the sum of first n natural numbers
def sum_of_natural_numbers(n):
return n * (n + 1) // 2 # Using the formula n(n + 1)/2

# Input value of n
n = int(input("Enter the value of n: "))
sum_n = sum_of_natural_numbers(n)
print(f"The sum of the first {n} natural numbers is: {sum_n}")

2. Write Python code to prints all integers between 1 to 100 that are divisible by 3
and 7.

-> # Printing all integers between 1 to 100 that are divisible by 3 and 7

print("Integers between 1 to 100 that are divisible by 3 and 7:")

for i in range(1, 101):

if i % 3 == 0 and i % 7 == 0:

print(i, end=' ')

print() # For newline after the output

3. Write Python code to prints all integers between 1 to n, which are relatively prime
to n.

-> from math import gcd


MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune

# Function to find all integers between 1 to n that are relatively prime to n

def relatively_prime(n):

result = []

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

if gcd(i, n) == 1:

result.append(i)

return result

# Input value of n

n = int(input("Enter the value of n: "))

relatively_prime_numbers = relatively_prime(n)

print(f"Integers between 1 to {n} that are relatively prime to {n}:


{relatively_prime_numbers}")
Q.2. Attempt any two of the following. [10]
1. Write Python code to find determinant, transpose and inverse of matrix.

1 2 3
A= 2 5 7
4 9 11
-> import numpy as np

# Define the matrix A


A = np.array([[1, 2, 3],
[2, 5, 7],
[4, 9, 11]])

# Calculate the determinant


determinant = np.linalg.det(A)

# Calculate the transpose


transpose = np.transpose(A)

# Calculate the inverse (if it exists)


try:
inverse = np.linalg.inv(A)
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune
except np.linalg.LinAlgError:
inverse = None

# Display results
print("Determinant of the matrix A:",
determinant)
print("Transpose of the matrix A:\n",
transpose)
print("Inverse of the matrix A:\n", inverse)

2. Write Python program to find the roots of the quadratic equation ax2 + bx + c = 0.

-> import cmath # Importing cmath to handle complex roots

# Function to find the roots of the quadratic equation

def quadratic_roots(a, b, c):

discriminant = b**2 - 4*a*c

root1 = (-b + cmath.sqrt(discriminant)) / (2*a)

root2 = (-b - cmath.sqrt(discriminant)) / (2*a)

return root1, root2

# Input coefficients

a = float(input("Enter coefficient a: "))

b = float(input("Enter coefficient b: "))

c = float(input("Enter coefficient c: "))

# Find the roots

roots = quadratic_roots(a, b, c)

print(f"The roots of the quadratic equation are: {roots[0]} and {roots[1]}")


MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune
3. Using Python solve the following system of equations using LU – Factorization
method

3x − 7y − 2z = −7
−3x + 5y + z = 5
6x − 4y = 2
-> import numpy as np
from scipy.linalg import lu, solve

# Coefficients of the system of equations


A = np.array([[3, -7, -2],
[-3, 5, 1],
[6, -4, 0]])
b = np.array([-7, 5, 2]) # Right-hand side

# LU Factorization
P, L, U = lu(A)

# Solve the system of equations


x = solve(A, b)

# Display the solution


print("Solution of the system of equations:")
print("x =", x[0], ", y =", x[1], ", z =", x[2])

Q.3. a. Attempt any one of the following. [7]


∫31
1. Write Python program to estimate the value of the integral 1 xdx by using Simp-
son’s ( 1 )rd rule (n=8).

− −

3
-> import numpy as np

# Function to integrate
def f(x):
return 1 # The function f(x) = 1 is a constant function

# Simpson's Rule Implementation


def simpsons_rule(a, b, n):
if n % 2 == 1: # n must be even
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune
n += 1

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

for i in range(1, n):


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

integral *= h / 3
return integral

# Estimate the integral from 1 to 3 using Simpson's Rule


a=1
b=3
n = 10 # Number of intervals
result = simpsons_rule(a, b, n)
print(f"Estimated value of the integral from {a} to {b} using Simpson's rule: {result}")
2. Write Python program to obtained the approximate real root of x4 8x2 4=0
using Regula-falsi method.

-> def f_regula_falsi(x):


return x**4 - 8*x**2 + 4 # Function

def regula_falsi(a, b, tol, max_iter):


if f_regula_falsi(a) * f_regula_falsi(b) >= 0:
print("No root found in the given interval.")
return None

for _ in range(max_iter):
c = b - (f_regula_falsi(b) * (a - b)) / (f_regula_falsi(a) - f_regula_falsi(b))
if abs(f_regula_falsi(c)) < tol:
return c
if f_regula_falsi(c) * f_regula_falsi(a) < 0:
b=c
else:
a=c

return c

# Parameters
a_rf = 0 # Lower bound
b_rf = 5 # Upper bound
tolerance_rf = 1e-6
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune
max_iterations_rf = 100

# Find the root using Regula-Falsi method


root_rf = regula_falsi(a_rf, b_rf, tolerance_rf, max_iterations_rf)
if root_rf is not None:
print("Approximate real root of x^4 - 8x^2 + 4 = 0:", root_rf)
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune

b. Attempt any one of the following. [8]


∫1
1. Write Python program to estimate the value of the integral x5dx using Trape-
0
zoidal rule (n=10).
-> # Function to integrate
def f(x):
return x**5 # The function f(x) = x^5

# Trapezoidal Rule Implementation


def trapezoidal_rule(a, b, n):
h = (b - a) / n
integral = 0.5 * (f(a) + f(b))

for i in range(1, n):


integral += f(a + i * h)

integral *= h
return integral

# Estimate the integral from 1 to 5 using Trapezoidal Rule


a=1
b=5
n = 10
result = trapezoidal_rule(a, b, n)
print(f"Estimated value of the integral from {a} to {b} using Trapezoidal rule:
{result}")

2. Write Python program to find sin(35)0 using Newton backward interpolation for-
mula for the data:
sin300 = 0.5, sin350 = 0.5736, sin400 = 0.6428, sin450 = 0.7071.
-> # Given data
x_data = np.array([30, 35, 40, 45])
y_data = np.array([0.5, 0.5736, 0.6428, 0.7071])

# Newton Backward Interpolation function


def newton_backward_interpolation(x, x_data, y_data):
n = len(x_data)
h = x_data[1] - x_data[0]
k = (x - x_data[-1]) / h

# Backward Difference Table


MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune
diff_table = np.zeros((n, n))
diff_table[:, 0] = y_data

for j in range(1, n):


for i in range(n - j):
diff_table[i][j] = diff_table[i + 1][j - 1] - diff_table[i][j - 1]

# Interpolation
result = diff_table[n - 1][0]
for j in range(1, n):
term = diff_table[n - j - 1][j]
for m in range(j):
term
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune

Savitribai Phule Pune University, Pune


Board of Studies in Mathematics
S.Y.B.Sc. (Computer Science)
Mathematics Practical Examination
MTC-233: Python Programming Language-I
(CBCS 2019 Pattern)(Semester-III )
Slip No.:-24

Time: 3 hour Maximum Marks: 35


Q.1. Attempt any two of the following. [10]
1. Write Python program to calculate the surface area of sphere A = 4πr2.
-> import math

# Function to calculate the surface area of a sphere


def surface_area_of_sphere(radius):
return 4 * math.pi * radius ** 2

# Input value of radius


radius = float(input("Enter the radius of the sphere: "))
surface_area = surface_area_of_sphere(radius)
print(f"The surface area of the sphere with radius {radius} is: {surface_area:.2f}")

2. Use Python code to find the remainder after dividing by ‘n’ to any integers.

-> # Function to find the remainder of a number divided by n

def find_remainder(num, n):

return num % n

# Input values

num = int(input("Enter an integer: "))

n = int(input("Enter a divisor: "))


MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune
remainder = find_remainder(num, n)

print(f"The remainder of {num} divided by {n} is: {remainder}")

3. Write Python program to prints all integers between 1 to 50 that are divisible by 3
and 7.

-> # Printing all integers between 1 to 50 that are divisible by 3 and 7

print("Integers between 1 to 50 that are divisible by 3 and 7:")

for i in range(1, 51):

if i % 3 == 0 and i % 7 == 0:

print(i, end=' ')

print() # For newline after the output

Q.2. Attempt any two of the following. [10]

1. Write Python program to find perfect square between 1 to 100.

-> # Finding perfect squares between 1 to 100

print("Perfect squares between 1 to 100:")

perfect_squares = [i**2 for i in range(1, 11)] # 1^2 to 10^2

print(perfect_squares)

2. Write Python program to prints whether the given natural number is divisible by 5
and less than 100.

-> # Function to check if a number is divisible by 5 and less than 100

def check_number(num):

if num < 100 and num % 5 == 0:

return True

return False

# Input value

num = int(input("Enter a natural number: "))


MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune
if check_number(num):

print(f"{num} is divisible by 5 and less than 100.")

else:

print(f"{num} is not divisible by 5 or is not less than 100.")

3. Write Python program to diagonalize the matrix

"
2 3#
−4 −6

and find matrix P and D.


-> import numpy as np

# Define the matrix


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

# Diagonalize the matrix (if possible)


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

# Matrix P (eigenvectors) and D (eigenvalues diagonal matrix)


P = eigenvectors
D = np.diag(eigenvalues)

# Display results
print("Matrix P (eigenvectors):\n", P)
print("Matrix D (eigenvalues diagonal matrix):\n", D)

Q.3. a. Attempt any one of the following. [7]


∫3
1. Write Python program to estimate the value of the integral 1 cos(x)dx using Simp-
son’s ( 3 )th rule (n=5).
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune
8
-> import numpy as np

# Function to integrate
def f(x):
return 3 * np.cos(x)

# Simpson's Rule Implementation


def simpsons_rule(a, b, n):
if n % 2 == 1: # n must be even
n += 1

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

for i in range(1, n):


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

integral *= h / 3
return integral

# Estimate the integral from 0 to π/2 using Simpson's Rule


a=0
b = np.pi / 2
n = 10 # Number of intervals
result = simpsons_rule(a, b, n)
print(f"Estimated value of the integral ∫3cos(x)dx from {a} to {b}: {result:.2f}")
2. Write Python program to evaluate f(1.9) by using backward difference formula of
the given data.
-> import numpy as np

# Given data
x_data = np.array([1, 2, 3, 4])
y_data = np.array([11, 10, 15, 10])

# Backward Difference Formula


def backward_difference(x, x_data, y_data):
n = len(x_data)
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune
h = x_data[1] - x_data[0]
k = int((x - x_data[0]) / h) # index for backward difference
if k >= n:
return None # Out of range

# Backward differences
diff_table = np.zeros((n, n))
diff_table[:, 0] = y_data

for j in range(1, n):


for i in range(n - j):
diff_table[i][j] = diff_table[i][j - 1] - diff_table[i + 1][j - 1]

# Interpolating value
result = diff_table[n - 1][0]
for j in range(1, k + 1):
term = diff_table[n - j - 1][j]
for m in range(j):
term *= (k - m) / (m + 1)
result += term

return result

# Evaluate f(1.9)
value_at_1_9 = backward_difference(1.9, x_data, y_data)
print(f"Value of f(1.9) using backward difference formula: {value_at_1_9:.2f}")

x 1 2 3 4
Y=f(x) 11 10 15 10
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune

b. Attempt any one of the following. [8]

1. Write Python program to obtained the approximate real root of x3 − 5x − 9 = 0 in


[2,4] using Regula-falsi method.

-> def f_regula_falsi(x):

return x**3 - 5*x - 9 # Function

def regula_falsi(a, b, tol, max_iter):

if f_regula_falsi(a) * f_regula_falsi(b) >= 0:

print("No root found in the given interval.")

return None

for _ in range(max_iter):

c = b - (f_regula_falsi(b) * (a - b)) / (f_regula_falsi(a) - f_regula_falsi(b))

if abs(f_regula_falsi(c)) < tol:

return c

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

b=c

else:

a=c

return c

# Parameters

a_rf = 2 # Lower bound

b_rf = 4 # Upper bound

tolerance_rf = 1e-6

max_iterations_rf = 100
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune

# Find the root using Regula-Falsi method

root_rf = regula_falsi(a_rf, b_rf, tolerance_rf, max_iterations_rf)

if root_rf is not None:

print("Approximate real root of x^3 - 5x - 9 = 0:", root_rf)

2. Write Python program to evaluate interpolate value f (17) of the given data.

-> # Given data for interpolation


x_data = np.array([12, 22, 32, 62])
y_data = np.array([25, 65, 125, 425])

# Newton's Forward Interpolation


def newton_forward_interpolation(x, x_data, y_data):
n = len(x_data)
h = x_data[1] - x_data[0]
k = int((x - x_data[0]) / h) # index for forward difference
if k >= n:
return None # Out of range

# Forward difference table


diff_table = np.zeros((n, n))
diff_table[:, 0] = y_data

for j in range(1, n):


for i in range(n - j):
diff_table[i][j] = diff_table[i + 1][j - 1] - diff_table[i][j - 1]

# Interpolating value
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune
result = y_data[0]
for j in range(1, k + 1):
term = diff_table[0][j]
for m in range(j):
term *= (k - m) / (m + 1)
result += term

return result

# Evaluate f(17)
value_at_17 = newton_forward_interpolation(17, x_data, y_data)
print(f"Interpolated value of f(17): {value_at_17:.2f

x 12 22 32 62
Y=f(x) 25 65 125 425
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune

Savitribai Phule Pune University, Pune


Board of Studies in Mathematics
S.Y.B.Sc. (Computer Science)
Mathematics Practical Examination
MTC-233: Python Programming Language-I
(CBCS 2019 Pattern)(Semester-III )
Slip No.:-25

Time: 3 hour Maximum Marks: 35


Q.1. Attempt any two of the following. [10]
1. Write Python program to print the integers between 1 and 1000 which are multiples
of 7.
-> # Printing integers between 1 and 1000 that are multiples of 7
print("Integers between 1 and 1000 that are multiples of 7:")
for i in range(1, 1001):
if i % 7 == 0:
print(i, end=' ')
print() # For newline after the output

2. Write Python program to prints whether the given number is divisible by 3 or 5 or


7.

-> # Function to check divisibility

def check_divisibility(num):

divisors = [3, 5, 7]

results = [d for d in divisors if num % d == 0]

return results

# Input value

num = int(input("Enter a number: "))

divisible_by = check_divisibility(num)

if divisible_by:
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune
print(f"{num} is divisible by: {', '.join(map(str, divisible_by))}")

else:

print(f"{num} is not divisible by 3, 5, or 7.")

3. Write Python code to find A + B and B ∗ A for the given Matrices.

4 2 4 5 2 3
A = 4 −1 1 & B = 3 −7 5
2 4 2 3 1 −1

-> import numpy as np

# Define matrices A and B


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

B = np.array([[5, 2, 3],
[3, 7, 5],
[3, 1, -1]])

# Adding A and B
# Note: Since A is 2x3 and B is
3x3, we cannot add them
directly.
# We will need to reshape A or
B to perform addition (if they
are compatible)
# Here we will perform addition
only if they are of the same
shape.
# Hence, we will print that they
are incompatible for addition.
try:
A_plus_B = A + B
print("A + B:\n", A_plus_B)
except ValueError as e:
print(f"Cannot add matrices
A and B: {e}")

# Multiplying A and B
B_times_A = np.dot(B, A) #
Matrix multiplication
print("B * A:\n", B_times_A)

Q.2. Attempt any two of the following. [10]


MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune

1. Write Python program to find the area and circumference of a circle with radius r.

-> import math

# Function to calculate area and circumference of a circle

def circle_properties(radius):

area = math.pi * radius ** 2


circumference = 2 * math.pi * radius

return area, circumference

# Input value for radius

radius = float(input("Enter the radius of the circle: "))

area, circumference = circle_properties(radius)

print(f"Area of the circle: {area:.2f}")

print(f"Circumference of the circle: {circumference:.2f}")

2. Use Python code to solve the following system of equations by gauss elimination
method

x + y + 2z = 7
−x − 2y + 3z = 6
3x − 7y + 6z = 1
-> import
numpy as np

# Coefficient
matrix
A=
np.array([[1, 1,
2],
[-1, -2,
3],
[3, -7,
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune

6]])

# Constants
B=
np.array([7, 6,
1])

# Solving the
system of
equations
using numpy
solution =
np.linalg.solve(
A, B)
print("Solution
(x, y, z):",
solution)

3. Write Python code to find eigen values, eigen vectors of the matrix and determine
whether the matrix is diagonalizable.

1 −1 1
A = −1 1 −1
1 −1 1

-> # Define the matrix A


A = np.array([[1, 1, 1],
[-1, 1, -1]])

# Finding eigenvalues and eigenvectors


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

# Check if the matrix is diagonalizable (if there are n linearly independent eigenvectors)
is_diagonalizable = len(eigenvalues) == len(set(eigenvalues))

# Display results
print("Eigenvalues:", eigenvalues)
print("Eigenvectors:\n", eigenvectors)
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune

print("Is the matrix diagonalizable?", is_diagonalizable)

Q.3. a. Attempt any one of the following.

[7]
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune

1. Write Python program to find the approximate root of the equation f (x) = x2 − 50
by using Newton Raphson method.
-> # Function f(x) = x^2 - 50
def f(x):
return x**2 - 50

# Derivative f'(x) = 2x
def f_derivative(x):
return 2*x

# Newton-Raphson method
def newton_raphson(initial_guess, tolerance, max_iterations):
x = initial_guess
for _ in range(max_iterations):
x_new = x - f(x) / f_derivative(x)
if abs(x_new - x) < tolerance:
return x_new
x = x_new
return x

# Parameters
initial_guess = 7.0
tolerance = 1e-6
max_iterations = 100

# Find the root


root = newton_raphson(initial_guess, tolerance, max_iterations)
print(f"Approximate root of the equation f(x) = x^2 - 50: {root:.4f}")

2. Write Python program to evaluate f(2.4) by forward difference formula of the given
data.
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune
-> import numpy as np

# Given data

x_data = np.array([0, 1, 2, 3])

y_data = np.array([11, 10, 11, 21])

# Forward Difference Formula

def forward_difference(x, x_data, y_data):

n = len(x_data)

h = x_data[1] - x_data[0]

k = int((x - x_data[0]) / h) # index for forward difference

if k >= n:

return None # Out of range

# Forward difference table

diff_table = np.zeros((n, n))

diff_table[:, 0] = y_data

for j in range(1, n):

for i in range(n - j):

diff_table[i][j] = diff_table[i + 1][j - 1] - diff_table[i][j - 1]

# Interpolating value

result = y_data[0]

for j in range(1, k + 1):

term = diff_table[0][j]
MTC-233 Python Programming Language-I Savitribai Phule Pune University, Pune
for m in range(j):

term *= (k - m) / (m + 1)

result += term

return result

# Evaluate f(2.4)

value_at_2_4 = forward_difference(2.4, x_data, y_data)

print(f"Value of f(2.4) using forward difference formula: {value_at_2_4:.2f}")

x 0 1 2 3
Y=f(x) 11 10 11 21

b. Attempt any one of the following. [8]


∫1
1. Write Python program to estimate the value of the integral 0 sin2(πx)dx using
Simpson’s ( 1 )rd rule (n=6).
-> from scipy.integrate import quad

# Function to integrate
def integrand(x):
return np.sin(np.pi * x) ** 2

# Estimate the integral from 0 to 1


integral_value, error = quad(integrand, 0, 1)
print(f"Estimated value of the integral ∫ sin²(πx)dx from 0 to 1:
{integral_value:.4f}")
2. Write Python program to find f(4) using Lagranges interpolation formula from the
data: f (1) = 6, f (2) = 9, f (5) = 30, f (7) = 54.
->

You might also like