SAVITRIBAI PHULE PUNE UNIVERSITY, PUNE Board of Studies in Mathematics S.Y.B.
Sc (Computer
Science) Practical Examination in Mathematics MTC-243: Python Programming Language-II (CBCS 2019
Pattern)(Semester-IV)
Slip No. : 01
Time: 3 Hours Max. Marks: 35
Q.1 Attempt any TWO of the following. [10]
(a) Write a Python program to plot 2D graph of the functions f(x) = x 2 and g(x) = x3 in [−1, 1]
import numpy as np
import matplotlib.pyplot as plt
# Create an array of x values from -1 to 1 with 1000 points
x = np.linspace(-1, 1, 1000)
# Calculate the corresponding y values for f(x) = x^2
y_f = x**2
# Calculate the corresponding y values for g(x) = x^3
y_g = x**3
# Create the plot
plt.figure(figsize=(8, 6))
# Plot f(x) = x^2
plt.plot(x, y_f, label='f(x) = x^2')
# Plot g(x) = x^3
plt.plot(x, y_g, label='g(x) = x^3')
# Add a legend
plt.legend()
# Add grid
plt.grid(True)
# Set the limits of the plot’s axes
plt.xlim(-1.1, 1.1)
plt.ylim(-1.1, 1.1)
# Add axis labels and title
plt.xlabel('x')
plt.ylabel('y')
plt.title('Graph of f(x) = x^2 and g(x) = x^3 in [-1, 1]')
# Show the plot
plt.show()
(b) Write a Python program to plot 3D graph of the function f(x) = e−x2 in [−5, 5] with green dashed
points line with upward pointing triangle.
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# Create an array of x values from -5 to 5 with 100 points
x = np.linspace(-5, 5, 100)
# Create an array of y values from -5 to 5 with 100 points
y = np.linspace(-5, 5, 100)
# Create a meshgrid of x and y values
X, Y = np.meshgrid(x, y)
# Calculate the corresponding z values using the function f(x, y) = e^(-x^2 - y^2)
Z = np.exp(-X**2 - Y**2)
# Create the 3D plot
fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(111, projection='3d')
# Plot the surface
ax.plot_surface(X, Y, Z, cmap='viridis', alpha=0.5)
# Plot the green dashed points line with upward pointing triangles
ax.plot(x, np.zeros_like(x), np.exp(-x**2), 'go', markersize=8, linestyle='--', marker='^', label='f(x)
= e^(-x^2)')
# Add a legend
ax.legend()
# Set the limits of the plot’s axes
ax.set_xlim(-5.1, 5.1)
ax.set_ylim(-0.1, 5.1)
ax.set_zlim(0, 1.1)
# Add axis labels and title
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('f(x, y)')
ax.set_title('Graph of f(x, y) = e^(-x^2 - y^2) in [-5, 5] with green dashed points line with upward
pointing triangles')
# Show the plot
plt.show()
(c) Using python, represent the following information using a bar graph (in green color )
Item clothing Food rent Petrol Misc.
expenditure in Rs 600 4000 2000 1500 700
import matplotlib.pyplot as plt
# Data
expenditure = {'clothing': 600, 'Food': 4000,
'rent': 2000, 'Petrol': 1500, 'Misc.': 700}
# Create a bar chart
plt.bar(expenditure.keys(),
expenditure.values(), color='green')
plt.title('Expenditure Breakdown')
plt.xlabel('Item')
plt.ylabel('Expenditure in Rs')
plt.show()
[10]
Q.2 Attempt any TWO of the following.
(a) Write a Python program to reflect the line segment joining the points A[5, 3] and B[1, 4] through
the line y = x + 1.
import matplotlib.pyplot as plt
# Define the original points A and B
A = (5, 3)
B = (1, 4)
# Define the line y = x + 1
line_x = np.linspace(-1, 6, 100)
line_y = line_x + 1
# Reflect the points A and B through the line y = x + 1
reflected_A = (B[0], 2*B[1] - A[1])
reflected_B = (A[0], 2*A[1] - B[1])
# Plot the original points, reflected points, and the line y = x + 1
plt.plot([A[0], B[0]], [A[1], B[1]], 'bo-', label='Original Line Segment')
plt.plot([reflected_A[0], reflected_B[0]], [reflected_A[1], reflected_B[1]], 'ro-', label='Reflected
Line Segment')
plt.plot(line_x, line_y, 'k--', label='y = x + 1')
plt.legend()
plt.xlabel('x')
plt.ylabel('y')
plt.show()
(b) Write a Python program to draw a polygon with vertices (0, 0), (2, 0), (2, 3) and (1, 6) and rotate
it by 180◦.
import matplotlib.pyplot as plt
import numpy as np
# Define the vertices of the polygon
vertices = np.array([[0, 0], [2, 0], [2, 3], [1, 6]])
# Plot the original polygon
plt.plot(vertices[:, 0], vertices[:, 1], 'bo-')
# Calculate the center of rotation
center = np.mean(vertices, axis=0)
# Calculate the rotation matrix
rotation_matrix = np.array([[np.cos(np.pi), -np.sin(np.pi)], [np.sin(np.pi), np.cos(np.pi)]])
# Rotate the vertices by 180 degrees
rotated_vertices = rotation_matrix @ (vertices - center) + center
# Plot the rotated polygon
plt.plot(rotated_vertices[:, 0], rotated_vertices[:, 1], 'ro-')
# Add labels and legend
plt.xlabel('x')
plt.ylabel('y')
plt.legend(['Original Polygon', 'Rotated Polygon'])
# Show the plot
plt.show()
(c) Write a Python program to find the area and perimeter of the ∆ABC, where A[0, 0], B[5, 0], C[3, 3].
import math
# Define the vertices of the triangle
A = (0, 0)
B = (5, 0)
C = (3, 3)
# Calculate the length of the sides using the distance formula
AB = math.sqrt((B[0] - A[0])**2 + (B[1] - A[1])**2)
BC = math.sqrt((C[0] - B[0])**2 + (C[1] - B[1])**2)
CA = math.sqrt((A[0] - C[0])**2 + (A[1] - C[1])**2)
# Calculate the semi-perimeter of the triangle
s = (AB + BC + CA) / 2
# Calculate the area of the triangle using Heron's formula
area = math.sqrt(s * (s - AB) * (s - BC) * (s - CA))
# Calculate the perimeter of the triangle
perimeter = AB + BC + CA
# Print the results
print("The area of the triangle is:", area)
print("The perimeter of the triangle is:", perimeter)
Q.3 Attempt the following.
(a) Attempt any ONE of the following. [7]
(i) Write a Python program to solve the following LPP:
Max Z = 150x + 75y
subject to 4x + 6y ≤ 24
5x + 3y ≤ 15
x ≥ 0, y ≥ 0.
import numpy as np
from scipy.optimize import linprog
# Define the objective function coefficients
c = np.array([150, 75])
# Define the constraint coefficients
A_ub = np.array([[4, 6], [5, 3]])
b_ub = np.array([24, 15])
# Define the bounds for the variables
bounds = [(0, None), (0, None)]
# Define the options for the linprog function
options = {'disp': True}
# Call the linprog function to solve the LPP
res = linprog(c, A_ub=A_ub, b_ub=b_ub, bounds=bounds, options=options)
# Print the results
print("Optimal solution found:")
print("x =", res.x[0])
print("y =", res.x[1])
print("Maximum value of Z =", res.fun)
(ii) Write a python program to display the following LPP by using pulp module and simplex
method. Find its optimal solution if exist.
Min Z = x + y
subject to x ≥ 6
y≥6
x + y ≤ 11
x ≥ 0, y ≥ 0.
import pulp
# Create a new LP problem
prob = pulp.LpProblem("Minimize_x_plus_y", pulp.LpMinimize)
# Define the variables
x = pulp.LpVariable("x", lowBound=0)
y = pulp.LpVariable("y", lowBound=0)
# Define the objective function
prob += x + y
# Define the constraints
prob += x >= 6
prob += y >= 6
prob += x + y <= 11
# Solve the problem using the simplex method
prob.solve()
# Print the results
print("Status:", pulp.LpStatus[prob.status])
print("Objective value:", prob.objective.value())
print("x:", x.varValue)
print("y:", y.varValue)
1
(b) Attempt any ONE of the following. [8]
(i) Apply Python program in each of the following transformations on the point P [3, −1]
(I) Refection through X−axis.
(II) Scaling in X−coordinate by factor 2.
(III) Scaling in Y−coordinate by factor 1.5.
(IV) Reflection through the line y = x.
# Define the point P
P = (3, -1)
# (I) Reflection through X-axis
P_reflected = (-P[0], P[1])
print("(I) Reflection through X-axis:",
P_reflected)
# (II) Scaling in X-coordinate by factor 2
P_scaled_x = (2 * P[0], P[1])
print("(II) Scaling in X-coordinate by factor
2:", P_scaled_x)
# (III) Scaling in Y-coordinate by factor 1.5
P_scaled_y = (P[0], 1.5 * P[1])
print("(III) Scaling in Y-coordinate by factor
1.5:", P_scaled_y)
# (IV) Reflection through the line y = x
if P[0] == P[1]:
P_reflected_y_x = (P[1], P[0])
else:
m = P[1] / P[0]
P_reflected_y_x = (1 / (m + 1), m / (m +
1))
print("(IV) Reflection through the line y =
x:", P_reflected_y_x)
(ii) Find the combined transformation of the line segment between the points A[5, −2] & B[4, 3]
by using Python program for the following sequence of transformations:-
(I) Rotation about origin through an angle π.
(II) Scaling in X− coordinate by 2 units.
(III) Reflection through the line y = −x.
(IV) Shearing in X direction by 4 units.
import numpy as np
# Define the points A and B
A = np.array([5, -2])
B = np.array([4, 3])
# (I) Rotation about origin through an
angle π
A_rotated = np.array([A[0] *
np.cos(np.pi) - A[1] * np.sin(np.pi),
A[0] * np.sin(np.pi) + A[1]
* np.cos(np.pi)])
B_rotated = np.array([B[0] *
np.cos(np.pi) - B[1] * np.sin(np.pi),
B[0] * np.sin(np.pi) + B[1]
* np.cos(np.pi)])
# (II) Scaling in X-coordinate by 2 units
A_scaled = np.array([2 * A_rotated[0],
A_rotated[1]])
B_scaled = np.array([2 * B_rotated[0],
B_rotated[1]])
# (III) Reflection through the line y = -x
A_reflected = np.array([-A_scaled[1], -
A_scaled[0]])
B_reflected = np.array([-B_scaled[1], -
B_scaled[0]])
# (IV) Shearing in X direction by 4 units
A_sheared = np.array([A_reflected[0] +
4 * A_reflected[1], A_reflected[1]])
B_sheared = np.array([B_reflected[0] +
4 * B_reflected[1], B_reflected[1]])
# Print the transformed points
print("Transformed points A and B:")
print("A:", A_sheared)
print("B:", B_sheared)
SAVITRIBAI PHULE PUNE UNIVERSITY, PUNE Board of Studies in Mathematics S.Y.B.Sc (Computer
Science) Practical Examination in Mathematics MTC-243: Python Programming Language-II (CBCS 2019
Pattern)(Semester-IV)
Slip No. : 02
Time: 3 Hours Max. Marks: 35
Q.1 Attempt any TWO of the following. [10]
(a) Write a Python program to plot 2D graph of the functions f(x) = log10(x) in the interval [0, 10].
import numpy as np
import matplotlib.pyplot as plt
# Define the function
def f(x):
return np.log10(x)
# Define the interval
x = np.linspace(0.1, 10, 100)
# Plot the function
plt.plot(x, f(x), label='f(x) = log10(x)')
# Set the plot title and labels
plt.title('Graph of f(x) = log10(x)')
plt.xlabel('x')
plt.ylabel('f(x)')
# Show the legend
plt.legend()
# Show the plot
plt.show()
(b) Using python, generate 3D surface Plot for the function f(x) = sin x 2 + y2 in the interval [0, 10].
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# Define the function
def f(x, y):
return np.sin(x**2 + y**2)
# Create a grid of x and y values
x = np.linspace(0, 10, 50)
y = np.linspace(0, 10, 50)
X, Y = np.meshgrid(x, y)
Z = f(X, Y)
# Create a 3D plot
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# Plot the surface
ax.plot_surface(X, Y, Z, cmap='viridis')
# Set the limits of the plot
ax.set_xlim(0, 10)
ax.set_ylim(0, 10)
ax.set_zlim(-1, 1)
# Show the plot
plt.show()
(c) Using python, draw a bar graph in GREEN colour to represent the data below:
Subject Maths Science English Marathi Hindi
Percentage of passing 68 90 70 85 91
import matplotlib.pyplot as plt
# Define the data
subjects = ['Maths', 'Science', 'English',
'Marathi', 'Hindi']
percentages = [68, 90, 70, 85, 91]
# Create a bar graph with green color
plt.bar(subjects, percentages, color='g')
# Set the title and labels
plt.title('Percentage of passing in different
subjects')
plt.xlabel('Subjects')
plt.ylabel('Percentage')
# Show the plot
plt.show()
Q.2 Attempt any TWO of the following. [10]
(a) Using sympy declare the points A(0, 2), B(5, 2), C(3, 0) check whether these points are collinear.
Declare the line passing through the points A and B, find the distance of this line from point C.
import sympy as sp
# Define the points
A = sp.Point(0, 2)
B = sp.Point(5, 2)
C = sp.Point(3, 0)
# Check if the points are collinear
if A.slope_to(B) == B.slope_to(C):
print("The points are collinear.")
else:
print("The points are not collinear.")
# Define the line passing through points A and B
line_AB = sp.Line(A, B)
# Find the distance of the line from point C
distance = line_AB.distance(C)
print("The distance of the line from point C is:", distance)
(b) Using python, drawn a regular polygon with 6 sides and radius 1 centered at (1, 2) and find its
area and perimeter.
import matplotlib.pyplot as plt
import sympy as sp
# Define the center of the polygon
center = sp.Point(1, 2)
# Define the radius of the polygon
radius = 1
# Define the number of sides of the polygon
n=6
# Calculate the apothem of the polygon
apothem = radius * sp.cos(sp.pi / n)
# Calculate the length of a side of the polygon
side_length = 2 * radius * sp.sin(sp.pi / n)
# Calculate the area of the polygon
area = n * apothem * side_length / 2
# Calculate the perimeter of the polygon
perimeter = n * side_length
# Define the vertices of the polygon
vertices = [center + radius * sp.Point(sp.cos(2 * sp.pi * i / n), sp.sin(2 * sp.pi * i / n)) for i in range(n)]
# Plot the polygon
plt.figure()
plt.axis('equal')
plt.plot([vertex.x for vertex in vertices], [vertex.y for vertex in vertices], 'b-')
plt.plot([center.x], [center.y], 'ro')
plt.text(center.x, center.y, 'Center', ha='center')
plt.show()
# Print the area and perimeter
print("The area of the polygon is:", area)
print("The perimeter of the polygon is:", perimeter)
(c) Write a Python program to find the area and perimeter of the ∆ABC, where A[0, 0], B[6, 0], C[4, 4].
import math
# Define the coordinates of the points
A = [0, 0]
B = [6, 0]
C = [4, 4]
# Calculate the lengths of the sides
AB = math.sqrt((B[0] - A[0])**2 + (B[1] - A[1])**2)
BC = math.sqrt((C[0] - B[0])**2 + (C[1] - B[1])**2)
CA = math.sqrt((A[0] - C[0])**2 + (A[1] - C[1])**2)
# Calculate the semi-perimeter
s = (AB + BC + CA) / 2
# Calculate the area using Heron's formula
area = math.sqrt(s * (s - AB) * (s - BC) * (s - CA))
# Calculate the perimeter
perimeter = AB + BC + CA
print("Area of the triangle:", area)
print("Perimeter of the triangle:", perimeter)
Q.3 Attempt the following.
(a) Attempt any ONE of the following. [7]
(i) Write a Python program to solve the following LPP:
Max Z = 5x + 3y
subject to x + y ≤ 7
2x + 5y ≤ 1
x ≥ 0, y ≥ 0.
from scipy.optimize import linprog
# Define the coefficients of the objective function
c = [-5, -3]
# Define the coefficients of the inequality constraints
A = [[1, 1], [2, 5]]
b = [7, 1]
# Define the bounds for the variables
bounds = [(0, None), (0, None)]
# Solve the LPP
res = linprog(c, A_ub=A, b_ub=b, bounds=bounds, method="highs")
# Print the results
print("Optimal solution:", res.x)
print("Maximum value of Z:", -res.fun)
(ii) Write a python program to display the following LPP by using pulp module and simplex
method. Find its optimal solution if exist.
Max Z = 3x + 2y + 5z
subject to x + 2y + z ≤ 430
3x + 2z ≤ 460
x + 4y ≤ 120
x ≥ 0, y ≥ 0, z ≥ 0.
import pulp as pp
# Define the problem
prob = pp.LpProblem('Optimization Problem', pp.LpMaximize)
# Define the decision variables
x = pp.LpVariable('x', 0, None, pp.LpContinuous)
y = pp.LpVariable('y', 0, None, pp.LpContinuous)
z = pp.LpVariable('z', 0, None, pp.LpContinuous)
# Define the objective function
prob += 3*x + 2*y + 5*z
# Define the constraints
prob += x + 2*y + z <= 430
prob += 3*x + 2*z <= 460
prob += x + 4*y <= 120
# Solve the problem using the simplex method
prob.solve()
# Print the optimal solution
print('Optimal solution:')
print('x =', pp.value(x))
print('y =', pp.value(y))
print('z =', pp.value(z))
print('Maximum value of Z =', pp.value(prob.objective))
(b) Attempt any ONE of the following. [8]
(i) Apply Python program in each of the following transformations on the point P [4, −2]
(I) Refection through Y−axis.
(II) Scaling in X−coordinate by factor 3.
(III) Scaling in Y−coordinate by factor 2.5
(IV) Reflection through the line y = −x.
import numpy as np
# Initial point P
P = np.array([4, -2])
print("Initial point P:", P)
# (I) Reflection through Y-axis
P_refl_y = np.array([-P[0], P[1]])
print("(I) Reflection through Y-axis:",
P_refl_y)
# (II) Scaling in X-coordinate by factor 3
P_scaled_x = np.array([3*P_refl_y[0],
P_refl_y[1]])
print("(II) Scaling in X-coordinate by factor
3:", P_scaled_x)
# (III) Scaling in Y-coordinate by factor 2.5
P_scaled_xy = np.array([P_scaled_x[0],
2.5*P_scaled_x[1]])
print("(III) Scaling in Y-coordinate by factor
2.5:", P_scaled_xy)
# (IV) Reflection through the line y = −x
P_refl_xy = np.array([P_scaled_xy[1], -
P_scaled_xy[0]])
print("(IV) Reflection through the line y =
−x:", P_refl_xy)
(ii) Find the combined transformation of the line segment between the points A[4, −1] & B[3, 0]
by using Python program for the following sequence of transformations:-
(I) Rotation about origin through an angle π.
(II) Shearing in Y direction by 4.5 units.
(III) Scaling in X− coordinate by 3 units.
(IV) Reflection through the line y = x.
import numpy as np
import matplotlib.pyplot as plt
# Initial points A and B
A = np.array([4, -1])
B = np.array([3, 0])
print("Initial points A and B:", A, B)
# (I) Rotation about origin through an angle π
def rotate(point, angle):
rotation_matrix = np.array([[np.cos(angle), -np.sin(angle)], [np.sin(angle), np.cos(angle)]])
return np.dot(rotation_matrix, point)
A_rot = rotate(A, np.pi)
B_rot = rotate(B, np.pi)
print("(I) Rotation about origin through an angle π:", A_rot, B_rot)
# (II) Shearing in Y direction by 4.5 units
def shear_y(point, shear_factor):
shear_matrix = np.array([[1, 0], [shear_factor, 1]])
return np.dot(shear_matrix, point)
A_shear = shear_y(A_rot, 4.5)
B_shear = shear_y(B_rot, 4.5)
print("(II) Shearing in Y direction by 4.5 units:", A_shear, B_shear)
# (III) Scaling in X-coordinate by 3 units
def scale_x(point, scale_factor):
scale_matrix = np.array([[scale_factor, 0], [0, 1]])
return np.dot(scale_matrix, point)
A_scaled = scale_x(A_shear, 3)
B_scaled = scale_x(B_shear, 3)
print("(III) Scaling in X-coordinate by 3 units:", A_scaled, B_scaled)
# (IV) Reflection through the line y = x
def reflect_xy(point):
reflection_matrix = np.array([[0, 1], [1, 0]])
return np.dot(reflection_matrix, point)
A_refl = reflect_xy(A_scaled)
B_refl = reflect_xy(B_scaled)
print("(IV) Reflection through the line y = x:", A_refl, B_refl)
# Plot the initial and transformed line segments
plt.figure(figsize=(8, 8))
plt.plot([A[0], B[0]], [A[1], B[1]], 'b-', label='Initial')
plt.plot([A_refl[0], B_refl[0]], [A_refl[1], B_refl[1]], 'r-', label='Transformed')
plt.xlabel('X')
plt.ylabel('Y')
plt.title('Combined Transformation of Line Segment')
plt.legend()
plt.grid(True)
plt.show()
SAVITRIBAI PHULE PUNE UNIVERSITY, PUNE Board of Studies in Mathematics S.Y.B.Sc (Computer
Science) Practical Examination in Mathematics MTC-243: Python Programming Language-II (CBCS 2019
Pattern)(Semester-IV)
Slip No. : 03
Time: 3 Hours Max. Marks: 35
Q.1 Attempt any TWO of the following. [10]
Using Python plot the graph of function f(x) = cos(x) on the interval [0, 2π].
import numpy as np
import matplotlib.pyplot as plt
# Generate x values in the interval [0, 2π]
x = np.linspace(0, 2 * np.pi, 100)
# Compute y values using the cosine function
y = np.cos(x)
# Create the plot
plt.figure(figsize=(8, 6))
plt.plot(x, y, label='f(x) = cos(x)')
# Set plot title and labels
plt.title('Graph of f(x) = cos(x) on the interval [0, 2π]')
plt.xlabel('x')
plt.ylabel('f(x)')
# Add grid and legend
plt.grid(True)
plt.legend()
# Show the plot
plt.show()
(b) Following is the information of students participating in various games in a school. Represent it
by a Bar graph with bar width of 0.7 inches.
import matplotlib.pyplot as plt
# Define the data
games = ['Cricket', 'Football', 'Hockey',
'Chess', 'Tennis']
num_students = [65, 30, 54, 10, 20]
# Create the bar graph
plt.figure(figsize=(10, 6))
plt.bar(games, num_students, width=0.7,
align='center')
# Set plot title and labels
plt.title('Number of Students Participating in
Games')
plt.xlabel('Games')
plt.ylabel('Number of Students')
# Show the plot
plt.show()
Game Cricket Football Hockey Chess Tennis
Number of students 65 30 54 10 20
Write a Python program to generate 3D plot of the functions z = sin x + cos y in −10 < x, y < 10.
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# Generate x and y values in the interval -10 < x, y < 10
x = np.linspace(-10, 10, 50)
y = np.linspace(-10, 10, 50)
X, Y = np.meshgrid(x, y)
# Compute z values using the function z = sin(x) + cos(y)
Z = np.sin(X) + np.cos(Y)
# Create the 3D plot
fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(X, Y, Z, cmap='viridis')
# Set plot title and labels
ax.set_title('3D Plot of z = sin(x) + cos(y) in -10 < x, y < 10')
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')
# Show the plot
(c) plt.show()
Q.2 Attempt any TWO of the following. [10]
(a) Write a Python program to reflect the line segment joining the points A[5, 3] & B[1, 4] through
the line y = x + 1
import math
# Define the points A and B
A = [5, 3]
B = [1, 4]
# Define the line y = x + 1
line = 1
# Calculate the slope of the line
m=1
# Calculate the mirror points A' and B'
A_prime = [A[0], 2*line - A[1]]
B_prime = [B[0], 2*line - B[1]]
# Calculate the reflected points C and D
C = [(A_prime[0] + B_prime[0])/2, (A_prime[1] + B_prime[1])/2]
D = [2*A[0] - C[0], 2*A[1] - C[1]]
# Print the reflected points C and D
print("The reflected points are:")
print("C =", C)
print("D =", D)
1 2
(b) If the line with points A[2, 1], B[4, −1] is transformed by the transformation matrix [T ] = 2 1,
then using python, find the equation of transformed line.
import numpy as np
# Define the points A and B
A = np.array([2, 1])
B = np.array([4, -1])
# Define the transformation matrix T
T = np.array([[1, 2],
[2, 1]])
# Transform the points A and B
A_transformed = np.dot(T, A)
B_transformed = np.dot(T, B)
# Calculate the slope of the transformed line
m_transformed = (B_transformed[1] - A_transformed[1]) / (B_transformed[0] - A_transformed[0])
# Calculate the y-intercept of the transformed line
b_transformed = A_transformed[1] - m_transformed * A_transformed[0]
# Print the equation of the transformed line
print("The equation of the transformed line is:")
if m_transformed == 0:
print("y =", b_transformed)
elif m_transformed == float('inf') or m_transformed == -float('inf'):
print("x =", A_transformed[0])
else:
print("y =", m_transformed, "x +", b_transformed)
(c) Generate line segment having endpoints (0, 0) and (10, 10) find midpoint of line
segment.
import matplotlib.pyplot as plt
# Define the endpoints of the line segment
endpoint1 = (0, 0)
endpoint2 = (10, 10)
# Generate the line segment
x_values = [endpoint1[0], endpoint2[0]]
y_values = [endpoint1[1], endpoint2[1]]
plt.plot(x_values, y_values)
# Find the midpoint of the line segment
midpoint = [(endpoint1[0] + endpoint2[0])/2, (endpoint1[1] + endpoint2[1])/2]
# Print the midpoint
print("The midpoint of the line segment is:", midpoint)
# Show the plot
plt.show()
Q.3 Attempt the following.
(a) Attempt any ONE of the following. [7]
(i) Write a Python program to solve the following LPP:
Min Z = 3.5x + 2y
subject to x + y ≥ 5
x≥4
y≤2
x ≥ 0, y ≥ 0.
import numpy as np
from scipy.optimize import linprog
# Define the objective function
c = np.array([3.5, 2])
# Define the constraints
A_ub = np.array([[1, 1], [1, 0], [0, 1], [-1, 0], [0, -1]])
b_ub = np.array([5, 4, 2, 0, 0])
# Define the bounds
bounds = [(0, None), (0, None)]
# Define the options
options = {'disp': True}
# Solve the LPP
res = linprog(c, A_ub=A_ub, b_ub=b_ub, bounds=bounds, options=options)
# Print the solution
print("Optimal solution found:")
print("x =", res.x[0])
print("y =", res.x[1])
print("Minimum value of Z =", res.fun)
(ii) Write a python program to display the following LPP by using pulp module and simplex
method. Find its optimal solution if exist.
Max Z = 3x1 + 5x2 + 4x3
subject to 2x1 + 3x2 ≤ 8
2x2 + 5x3 ≤ 10
3x1 + 2x2 + 4x3 ≤ 15
x1 ≥ 0, x2 ≥ 0, x3 ≥ 0.
import pulp as p
# Define the problem
prob = p.LpProblem('Maximize', p.LpMaximize)
# Define the decision variables
x1 = p.LpVariable('x1', 0, None)
x2 = p.LpVariable('x2', 0, None)
x3 = p.LpVariable('x3', 0, None)
# Define the objective function
prob += 3*x1 + 5*x2 + 4*x3
# Define the constraints
prob += 2*x1 + 3*x2 <= 8
prob += 2*x2 + 5*x3 <= 10
prob += 3*x1 + 2*x2 + 4*x3 <= 15
# Solve the problem using the simplex method
prob.solve()
# Print the optimal solution
print('Optimal solution:')
print('Objective function value:', prob.objective.value())
print('x1:', x1.varValue)
print('x2:', x2.varValue)
print('x3:', x3.varValue)
5
(b) Attempt any ONE of the following. [8]
(i) Apply Python program in each of the following transformations on the point P [4, −2]
(I) Refection through Y−axis.
(II) Scaling in X−coordinate by factor 3.
(III) Scaling in Y−coordinate by factor 2.5
(IV) Reflection through the line y = −x.
# Transformation (I): Reflection through Y-
axis
def reflect_y_axis(point):
return [-point[0], point[1]]
P_reflected = reflect_y_axis([4, -2])
print("Point after reflection through Y-
axis:", P_reflected)
# Transformation (II): Scaling in X-
coordinate by factor 3
def scale_x(point, factor):
return [factor * point[0], point[1]]
P_scaled = scale_x([4, -2], 3)
print("Point after scaling X-coordinate by
3:", P_scaled)
# Transformation (III): Scaling in Y-
coordinate by factor 2.5
def scale_y(point, factor):
return [point[0], factor * point[1]]
P_scaled = scale_y(P_scaled, 2.5)
print("Point after scaling Y-coordinate by
2.5:", P_scaled)
# Transformation (IV): Reflection through
the line y = -x
def reflect_y_minus_x(point):
return [-point[1], -point[0]]
P_reflected =
reflect_y_minus_x(P_scaled)
print("Point after reflection through the line
y = -x:", P_reflected)
(ii) Find the combined transformation of the line segment between the points A[2, −1] & B[5, 4]
by using Python program for the following sequence of transformations:-
(I) Rotation about origin through an angle π.
(II) Scaling in X−coordinate by 3 units.
(III) Shearing in X direction by 6 units.
(IV) Reflection through the line y = x.
# Transformation (I): Rotation about origin through an angle π
def rotate_pi(point):
x, y = point
return [-x, -y]
A_rotated = rotate_pi([2, -1])
B_rotated = rotate_pi([5, 4])
# Transformation (II): Scaling in X-coordinate by 3 units
def scale_x(point, factor):
x, y = point
return [factor * x, y]
A_scaled = scale_x(A_rotated, 3)
B_scaled = scale_x(B_rotated, 3)
# Transformation (III): Shearing in X direction by 6 units
def shear_x(point, factor):
x, y = point
return [x + factor * y, y]
A_sheared = shear_x(A_scaled, 6)
B_sheared = shear_x(B_scaled, 6)
# Transformation (IV): Reflection through the line y = x
def reflect_y_equals_x(point):
x, y = point
return [y, x]
A_reflected = reflect_y_equals_x(A_sheared)
B_reflected = reflect_y_equals_x(B_sheared)
# Print the resulting points after each transformation
print("Point A after rotation:", A_rotated)
print("Point B after rotation:", B_rotated)
print("Point A after scaling:", A_scaled)
print("Point B after scaling:", B_scaled)
print("Point A after shearing:", A_sheared)
print("Point B after shearing:", B_sheared)
print("Point A after reflection:", A_reflected)
print("Point B after reflection:", B_reflected)
6
SAVITRIBAI PHULE PUNE UNIVERSITY, PUNE Board of Studies in Mathematics S.Y.B.Sc (Computer
Science) Practical Examination in Mathematics MTC-243: Python Programming Language-II (CBCS 2019
Pattern)(Semester-IV)
Slip No. : 04
Time: 3 Hours Max. Marks: 35
Q.1 Attempt any TWO of the following. [10]
(a) Write a Python program to plot 2D graph of the functions f(x) = log10(x) in the interval [0, 10].
import numpy as np
import matplotlib.pyplot as plt
# Define the function
def f(x): [10]
return np.log10(x)
3 −2
,
# Generate x values 2 1
x = np.linspace(0, 10, 1000)
# Generate y values
y = f(x)
# Create the plot
plt.plot(x, y)
# Set the title and labels
plt.title('2D Graph of f(x) = log10(x) in the interval [0, 10]')
plt.xlabel('x')
plt.ylabel('f(x)')
# Show the plot
plt.show()
(b) Using Python plot the graph of function f(x) = sin−1(x) on the interval [−1, 1].
import numpy as np
import matplotlib.pyplot as plt
# Define the function
def f(x):
return np.arcsin(x)
# Generate x values
x = np.linspace(-1, 1, 1000)
# Generate y values
y = f(x)
# Create the plot
plt.plot(x, y)
# Set the title and labels
plt.title('Graph of f(x) = sin^(-1)(x) on the interval [-1, 1]')
plt.xlabel('x')
plt.ylabel('f(x)')
# Show the plot
plt.show()
(c) Using Python plot the surface plot of parabola z = x2 + y2 in −6 < x, y < 6.
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# Generate x, y values
x = np.linspace(-6, 6, 30)
y = np.linspace(-6, 6, 30)
X, Y = np.meshgrid(x, y)
# Generate z values
Z = X**2 + Y**2
# Create the plot
fig = plt.figure()
axes = fig.gca(projection='3d')
axes.plot_surface(X, Y, Z, cmap='viridis')
# Set the title and labels
axes.set_title('Surface Plot of Parabola z = x^2 + y^2 in -6 < x, y < 6')
axes.set_xlabel('X')
axes.set_ylabel('Y')
axes.set_zlabel('Z')
# Show the plot
plt.show()
Q.2 Attempt any TWO of the following.
(a) If the line with points A[3, 1], B[5, −1] is transformed by the transformation matrix [T ] =
then using python, find the equation of transformed line.
import numpy as np
# Define the original points
A = np.array([3, 1])
B = np.array([5, -1])
# Define the transformation matrix
T = np.array([[2, 2], [3, 3]])
# Transform the points
transformed_A = np.dot(T, A)
transformed_B = np.dot(T, B)
# Print the transformed points
print("Transformed points:")
print(f"A' = {transformed_A}")
print(f"B' = {transformed_B}")
# Find the slope of the transformed line
m = (transformed_B[1] - transformed_A[1]) / (transformed_B[0] - transformed_A[0])
# Find the y-intercept of the transformed line
c = transformed_A[1] - m * transformed_A[0]
# Print the equation of the transformed line
print("Equation of the transformed line:")
print(f"y = {m}x {c}")
(b) Write a Python program to draw a polygon with vertices (0, 0), (2, 0), (2, 3) and (1, 6) and rotate
it by 180◦.
import turtle
# Create a new turtle screen
screen = turtle.Screen()
screen.bgcolor("white")
# Create a new turtle object
turtle = turtle.Turtle()
turtle.speed(0)
# Draw the polygon
turtle.penup()
turtle.goto(0, 0)
turtle.pendown()
turtle.begin_fill()
turtle.goto(2, 0)
turtle.goto(2, 3)
turtle.goto(1, 6)
turtle.goto(0, 0)
turtle.end_fill()
# Rotate the polygon by 180 degrees
turtle.penup()
turtle.goto(0, 0)
turtle.pendown()
turtle.left(180)
# Draw the rotated polygon
turtle.begin_fill()
turtle.goto(2, 0)
turtle.goto(2, 3)
turtle.goto(1, 6)
turtle.goto(0, 0)
turtle.end_fill()
# Hide the turtle object
turtle.hideturtle()
# Close the turtle screen
turtle.done()
(c) Using python, generate line passing through points (2, 3) and (4, 3) and find equation of the line.
# Define the points as tuples
point1 = (2, 3)
point2 = (4, 3)
# Calculate the slope of the line
m = (point2[1] - point1[1]) / (point2[0] - point1[0])
# Calculate the y-intercept of the line
c = point1[1] - m * point1[0]
# Print the equation of the line
print("Equation of the line:")
print(f"y = {m}x {c}")
Q.3 Attempt the following.
(a) Attempt any ONE of the following. [7]
(i) Write a Python program to solve the following LPP:
Max Z = 150x + 75y
subject to 4x + 6y ≤ 24
5x + 3y ≤ 15
x ≥ 0, y ≥ 0.
import numpy as np
from scipy.optimize import linprog
# Define the objective function coefficients
c = np.array([150, 75])
# Define the constraint coefficients
A_ub = np.array([[4, 6], [5, 3]])
# Define the constraint bounds
b_ub = np.array([24, 15])
# Define the variable bounds
bounds = [(0, None), (0, None)]
# Define the linprog arguments
args = (A_ub, b_ub)
# Solve the LPP
res = linprog(c=c, A_ub=A_ub, b_ub=b_ub, bounds=bounds, method='simplex')
# Print the solution
print("Optimal solution:")
print(f"x = {res.x[0]:.2f}")
print(f"y = {res.x[1]:.2f}")
print(f"Maximum value of Z = {res.fun:.2f}")
(ii) Write a python program to display the following LPP by using pulp module and simplex
method. Find its optimal solution if exist.
Max Z = 4x + y + 3z + 5w
subject to 4x + 6y − 5z − 4w ≥ −20
−8x − 3y + 3z + 2w ≤ 20
x + y ≤ 11
x ≥ 0, y ≥ 0, z ≥ 0, w ≥ 0.
import pulp
# Create a new LpProblem object
prob = pulp.LpProblem("LPP", pulp.LpMaximize)
# Define the decision variables
x = pulp.LpVariable("x", lowBound=0)
y = pulp.LpVariable("y", lowBound=0)
z = pulp.LpVariable("z", lowBound=0)
w = pulp.LpVariable("w", lowBound=0)
# Define the objective function
prob += 4*x + y + 3*z + 5*w
# Define the constraints
prob += 4*x + 6*y - 5*z - 4*w >= -20
prob += -8*x - 3*y + 3*z + 2*w <= 20
prob += x + y <= 11
# Solve the problem using the simplex method
prob.solve()
# Print the results
print("Optimal solution:")
print("x = ", x.varValue)
print("y = ", y.varValue)
print("z = ", z.varValue)
print("w = ", w.varValue)
print("Maximum value of Z = ", prob.objective.value())
7
(b) Attempt any ONE of the following. [8]
(i) Plot 3D axes with labels as x−axis and z−axis and also plot following points with given
coordinates in one graph.
(I) (70, −25, 15) as a diamond in black colour,
(II) (50, 72, −45) as a ∗ in green colour,
(III) (58, −82, 65) as a dot in green colour,
(IV) (20, 72, −45) as a ∗ in Red colour.
import matplotlib.pyplot as plt
import numpy as np
# Create figure and axes
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# Set labels for x, y, and z axes
ax.set_xlabel('X-axis')
ax.set_ylabel('Z-axis')
# Plot point I
ax.scatter(70, -25, 15, marker='D',
color='black', label='Point I')
# Plot point II
ax.scatter(50, 72, -45, marker='*',
color='green', label='Point II')
# Plot point III
ax.scatter(58, -82, 65, marker='.',
color='green', label='Point III')
# Plot point IV
ax.scatter(20, 72, -45, marker='*',
color='red', label='Point IV')
# Add legend
ax.legend()
# Show plot
plt.show()
(ii) Find the combined transformation of the line segment between the points A[4, −1] & B[3, 0]
by using Python program for the following sequence of transformations:-
(I) Shearing in X direction by 9 units.
(II) Rotation about origin through an angle π.
(III) Scaling in X− coordinate by 2 units.
(IV) Reflection through the line y = x.
import numpy as np
# Define the original points
A = np.array([4, -1])
B = np.array([3, 0])
# Define the transformation matrices
S = np.array([[1, 9], [0, 1]]) # shearing in X direction by 9 units
R = np.array([[np.cos(np.pi), -np.sin(np.pi)], [np.sin(np.pi), np.cos(np.pi)]]) # rotation about origin through an angle
π
S_prime = np.array([[2, 0], [0, 1]]) # scaling in X-coordinate by 2 units
M = np.array([[0, 1], [1, 0]]) # reflection through the line y = x
# Apply the transformations
A_transformed = np.dot(M, np.dot(S_prime, np.dot(R, np.dot(S, A))))
B_transformed = np.dot(M, np.dot(S_prime, np.dot(R, np.dot(S, B))))
# Print the transformed points
print("Transformed points:")
print("A = ", A_transformed)
print("B = ", B_transformed)
8
SAVITRIBAI PHULE PUNE UNIVERSITY, PUNE Board of Studies in Mathematics S.Y.B.Sc (Computer
Science) Practical Examination in Mathematics MTC-243: Python Programming Language-II (CBCS 2019
Pattern)(Semester-IV)
Slip No. : 05
Time: 3 Hours Max. Marks: 35
Q.1 Attempt any TWO of the following. [10]
2 2
(a) Using Python plot the surface plot of function z = cos x + y − 0.5 in the interval from −1 <
x, y < 1.
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
x = np.linspace(-1, 1, 100)
y = np.linspace(-1, 1, 100)
x, y = np.meshgrid(x, y)
z = np.cos(x**2 + y**2) - 0.5
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(x, y, z, cmap='viridis')
plt.show()
Generate 3D surface Plot for the function f(x) = sin x2 + y2 in the interval [0, 10].
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
x_values = np.linspace(0, 10, 100)
y_values = np.linspace(0, 10, 100)
x_values, y_values = np.meshgrid(x_values, y_values)
z_values = np.sin(x_values**2 + y_values**2)
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(x_values, y_values, z_values, cmap='viridis')
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
ax.set_title('Surface Plot of f(x) = sin(x^2 + y^2)')
plt.show()
(c) Write a Python program to generate 3D plot of the functions z = sin x + cos y in the interval −10
< x, y < 10.
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
x = np.linspace(-10, 10, 100)
y = np.linspace(-10, 10, 100)
x, y = np.meshgrid(x, y)
z = np.sin(x) + np.cos(y)
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(x, y, z, cmap='viridis')
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
ax.set_title('Surface Plot of z = sin x + cos y')
plt.show()
Q.2 Attempt any TWO of the following. [10]
(a) Using python, generate triangle with vertices (0, 0), (4, 0), (4, 3) check whether the triangle is
Right angle triangle.
import math
# Calculate the lengths of the three sides
a = math.sqrt((4 - 0)**2 + (0 - 0)**2)
b = math.sqrt((4 - 4)**2 + (3 - 0)**2)
c = math.sqrt((4 - 0)**2 + (3 - 0)**2)
# Check if the triangle is a right-angle triangle
if a**2 + b**2 == c**2:
print("The triangle is a right-angle triangle.")
else:
print("The triangle is not a right-angle triangle.")
(b) Generate vector x in the interval [−7, 7] using numpy package with 50 subintervals.
import numpy as np
x = np.linspace(-7, 7, 50)
print(x)
(c) Write a Python program to find the area and perimeter of the ∆ABC, where A[0, 0], B[6, 0], C[4, 4].
import math
# Define the vertices of the triangle
A = (0, 0)
B = (6, 0)
C = (4, 4)
# Calculate the length of the sides
a = math.sqrt((B[0] - A[0])**2 + (B[1] - A[1])**2)
b = math.sqrt((C[0] - B[0])**2 + (C[1] - B[1])**2)
c = math.sqrt((A[0] - C[0])**2 + (A[1] - C[1])**2)
# Calculate the semi-perimeter
s = (a + b + c) / 2
# Calculate the area using Heron's formula
area = math.sqrt(s * (s - a) * (s - b) * (s - c))
# Calculate the perimeter
perimeter = a + b + c
# Print the results
print("Area of the triangle: {:.2f}".format(area))
print("Perimeter of the triangle: {:.2f}".format(perimeter))
Q.3 Attempt the following.
(a) Attempt any ONE of the following. [7]
(i) Write a Python program to solve the following LPP:
Max Z = 5x + 3y
subject to x + y ≤ 7
2x + 5y ≤ 1
x ≥ 0, y ≥ 0.
import numpy as np
from scipy.optimize import linprog
# Define the objective function coefficients
c = np.array([5, 3])
# Define the constraint matrix
A = np.array([[1, 1], [2, 5]])
# Define the constraint bounds
b = np.array([7, 1])
# Define the variable bounds
bounds = [(0, None), (0, None)]
# Solve the LPP
res = linprog(c=c, A_ub=A, b_ub=b, bounds=bounds, method='simplex')
# Print the results
print("Optimal solution: x = {:.2f}, y = {:.2f}".format(res.x[0], res.x[1]))
print("Maximum value of Z: {:.2f}".format(res.fun))
(ii) Write a python program to display the following LPP by using pulp module and simplex
method. Find its optimal solution if exist.
Max Z = 4x + y + 3z + 5w
subject to 4x + 6y − 5z − 4w ≥ 20
−3x − 2y + 4z + w ≤ 10
−8x − 3y + 3z + 2w ≤ 20
x + y ≤ 11
x ≥ 0, y ≥ 0, z ≥ 0, w ≥ 0.
import pulp
# Define the problem
prob = pulp.LpProblem("LPP", pulp.LpMaximize)
# Define the decision variables
x = pulp.LpVariable("x", 0, None, pulp.LpContinuous)
y = pulp.LpVariable("y", 0, None, pulp.LpContinuous)
z = pulp.LpVariable("z", 0, None, pulp.LpContinuous)
w = pulp.LpVariable("w", 0, None, pulp.LpContinuous)
# Define the objective function
prob += 4*x + y + 3*z + 5*w
# Define the constraints
prob += 4*x + 6*y - 5*z - 4*w >= 20
prob += -3*x - 2*y + 4*z + w <= 10
prob += -8*x - 3*y + 3*z + 2*w <= 20
prob += x + y <= 11
# Solve the problem using the Simplex method
prob.solve()
# Print the results
print("Status:", pulp.LpStatus[prob.status])
print("Optimal solution: x = {}, y = {}, z = {}, w = {}".format(x.varValue, y.varValue, z.varValue, w.varValue))
print("Maximum value of Z: {:.2f}".format(prob.objective.value()))
9
(b) Attempt any ONE of the following. [8]
(i) Apply Python program in each of the following transformations on the point P [3, 8]
(I) Refection through X−axis.
(II) Scaling in X−coordinate by factor 6.
(III) Rotation about origin through an angle 30◦.
(IV) Reflection through the line y = −x.
# Define the point P
P = (3, 8)
# Transformation I: Reflection through X-axis
P_I = (-P[0], P[1])
print("Transformation I: P_I =", P_I)
# Transformation II: Scaling in X-coordinate by
factor 6
P_II = (6*P[0], P[1])
print("Transformation II: P_II =", P_II)
# Transformation III: Rotation about origin
through an angle 30 degrees
import math
theta = math.radians(30)
P_III = (P[0]*math.cos(theta) -
P[1]*math.sin(theta), P[0]*math.sin(theta) +
P[1]*math.cos(theta))
print("Transformation III: P_III =", P_III)
# Transformation IV: Reflection through the line
y = -x
P_IV = (-P[1], -P[0])
print("Transformation IV: P_IV =", P_IV)
(ii) Write a python program to Plot 2D X−axis and Y−axis in black colour. In the same diagram
plot:-
(I) Green triangle with vertices [5, 4], [7, 4], [6, 6].
(II) Blue rectangle with vertices [2, 2], [10, 2], [10, 8], [2, 8].
(III) Red polygon with vertices [6, 2], [10, 4], [8, 7], [4, 8], [2,
4]. (IV) Isosceles triangle with vertices [0, 0], [4, 0], [2, 4].
import matplotlib.pyplot as plt
# Define the vertices of the shapes
vertices_I = [(5, 4), (7, 4), (6, 6)]
vertices_II = [(2, 2), (10, 2), (10, 8), (2, 8)]
vertices_III = [(6, 2), (10, 4), (8, 7), (4, 8), (2, 4)]
vertices_IV = [(0, 0), (4, 0), (2, 4)]
# Plot the X and Y axes
plt.axhline(y=0, color='black', linestyle='-')
plt.axvline(x=0, color='black', linestyle='-')
# Plot the shapes
plt.plot([v[0] for v in vertices_I], [v[1] for v in vertices_I], 'g-', label='Triangle I')
plt.plot([v[0] for v in vertices_II], [v[1] for v in vertices_II], 'b-', label='Rectangle II')
plt.plot([v[0] for v in vertices_III], [v[1] for v in vertices_III], 'r-', label='Polygon III')
plt.plot([v[0] for v in vertices_IV], [v[1] for v in vertices_IV], 'k-', label='Triangle IV')
# Add a legend
plt.legend()
# Show the plot
plt.show()
10
SAVITRIBAI PHULE PUNE UNIVERSITY, PUNE Board of Studies in Mathematics S.Y.B.Sc (Computer
Science) Practical Examination in Mathematics MTC-243: Python Programming Language-II (CBCS 2019
Pattern)(Semester-IV)
Slip No. : 06
Time: 3 Hours Max. Marks: 35
Q.1 Attempt any TWO of the following. [10]
(a) Draw the horizontal bar graph for the following data in Maroon colour.
City Pune Mumbai Nasik Nagpur Thane
Air Quality Index 168 190 170 178 195
import matplotlib.pyplot as plt
# Define the data
cities = ['Pune', 'Mumbai', 'Nasik', 'Nagpur', 'Thane']
AQI = [168, 190, 170, 178, 195]
# Define the color of the bars
color = 'maroon'
# Create a horizontal bar graph
plt.barh(cities, AQI, color=color)
# Add a title and labels
plt.title('Air Quality Index of Cities', color='black')
plt.xlabel('Air Quality Index', color='black')
plt.ylabel('Cities', color='black')
# Show the plot
plt.show()
(b) Using python, generate 3D surface Plot for the function f(x) = sin x 2 + y2 in the interval [0, 10].
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
x = np.linspace(0, 10, 100)
y = np.linspace(0, 10, 100)
X, Y = np.meshgrid(x, y)
Z = np.sin(X**2 + Y**2)
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(X, Y, Z, cmap='viridis')
ax.set_title('3D Surface Plot of f(x) = sin(x^2 + y^2)')
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
plt.show()
(c) Using Python, plot the graph of function f(x) = sin(x) −ex + 3x2 −log10(x) on the Interval [0, 2π].
import numpy as np
import matplotlib.pyplot as plt
# Define the function
def f(x):
return np.sin(x) - np.exp(x) + 3*x**2 - np.log10(x)
# Generate x values from 0 to 2*pi with 1000 points
x = np.linspace(0, 2*np.pi, 1000)
# Generate y values using the function
y = f(x)
# Plot the graph
plt.plot(x, y)
plt.xlabel('x')
plt.ylabel('f(x)')
plt.title('Graph of f(x) = sin(x) - e^x + 3x^2 - log10(x) on [0, 2π]')
plt.grid(True)
plt.show()
Q.2 Attempt any TWO of the following. [10]
(a) Using python, rotate the line segment by 180◦ having end points (1, 0) and (2, −1).
import numpy as np
import matplotlib.pyplot as plt
# Define the end points of the line segment
x1, y1 = 1, 0
x2, y2 = 2, -1
# Calculate the rotation matrix
rotation_matrix = np.array([[-1, 0],
[0, -1]])
# Rotate the line segment
x1_rotated, y1_rotated = np.dot(rotation_matrix, np.array([x1, y1]))
x2_rotated, y2_rotated = np.dot(rotation_matrix, np.array([x2, y2]))
# Plot the original line segment
plt.plot([x1, x2], [y1, y2], 'b-', label='Original Line Segment')
# Plot the rotated line segment
plt.plot([x1_rotated, x2_rotated], [y1_rotated, y2_rotated], 'r-', label='Rotated Line Segment')
# Add a legend
plt.legend()
# Show the plot
plt.show()
(b) Write a Python program to draw a polygon with vertices (0, 0), (2, 0), (2, 3) and (1, 6) and rotate
it by 180◦.
import turtle
# Create a new turtle object
t = turtle.Turtle()
# Draw a polygon with vertices (0, 0), (2, 0), (2, 3), and (1, 6)
t.penup()
t.goto(0, 0)
t.pendown()
t.goto(2, 0)
t.goto(2, 3)
t.goto(1, 6)
t.goto(0, 0)
# Rotate the turtle (and the polygon it drew) by 180 degrees
t.right(180)
# Hide the turtle
t.hideturtle()
# Keep the window open until the user closes it
turtle.done()
(c) Using python, generate triangle with vertices (0, 0), (4, 0), (2, 4), check whether the triangle is
isosceles triangle.
import math
# Define the vertices of the triangle
vertex1 = (0, 0)
vertex2 = (4, 0)
vertex3 = (2, 4)
# Calculate the lengths of the sides of the triangle
side1 = math.sqrt((vertex2[0] - vertex1[0])**2 + (vertex2[1] - vertex1[1])**2)
side2 = math.sqrt((vertex3[0] - vertex1[0])**2 + (vertex3[1] - vertex1[1])**2)
side3 = math.sqrt((vertex3[0] - vertex2[0])**2 + (vertex3[1] - vertex2[1])**2)
# Check if the triangle is isosceles
if (side1 == side2) or (side2 == side3) or (side1 == side3):
print("The triangle is isosceles.")
else:
print("The triangle is not isosceles.")
Q.3 Attempt the following.
(a) Attempt any ONE of the following. [7]
(i) Write a Python program to solve the following LPP:
Max Z = x + y
subject to 2x − 2y ≥ 1
x+y≥2
x ≥ 0, y ≥ 0.
from pulp import *
# Create a new LP problem
prob = LpProblem("Maximize Z", LpMaximize)
# Define the decision variables
x = LpVariable("x", 0, None, LpContinuous)
y = LpVariable("y", 0, None, LpContinuous)
# Define the objective function
prob += x + y
# Define the constraints
prob += 2*x - 2*y >= 1
prob += x + y >= 2
# Solve the problem
prob.solve()
# Print the results
print("Status:", LpStatus[prob.status])
print("Optimal Solution: x =", x.value(), ", y =", y.value())
print("Optimal Value of Z: ", value(prob.objective))
(ii) Write a python program to display the following LPP by using pulp module and simplex
method. Find its optimal solution if exist.
Min Z = x + y
subject to x ≥ 6
y≥6
x + y ≤ 11
x ≥ 0, y ≥ 0.
from pulp import *
# Create a new LP problem
prob = LpProblem("Minimize Z", LpMinimize)
# Define the decision variables
x = LpVariable("x", 0, None, LpContinuous)
y = LpVariable("y", 0, None, LpContinuous)
# Define the objective function
prob += x + y
# Define the constraints
prob += x >= 6
prob += y >= 6
prob += x + y <= 11
# Solve the problem using the simplex method
prob.solve()
# Print the results
print("Status:", LpStatus[prob.status])
print("Optimal Solution: x =", x.value(), ", y =", y.value())
print("Optimal Value of Z: ", value(prob.objective))
11
(b) Attempt any ONE of the following. [8]
(i) Apply Python program in each of the following transformations on the point P [4, −2]
(I) Refection through Y−axis.
P = [4, -2]
reflection_matrix = [[-1, 0], [0, 1]]
P_reflected = [reflection_matrix[0][0]*P[0] + reflection_matrix[0][1]*P[1],
reflection_matrix[1][0]*P[0] + reflection_matrix[1][1]*P[1]]
print("Reflected point:", P_reflected)
(II) Scaling in X−coordinate by factor 7.
P = [4, -2]
scaling_matrix = [[7, 0], [0, 1]]
P_scaled = [scaling_matrix[0][0]*P[0] + scaling_matrix[0][1]*P[1],
scaling_matrix[1][0]*P[0] + scaling_matrix[1][1]*P[1]]
print("Scaled point:", P_scaled)
(III) Shearing in Y direction by 3 units
P = [4, -2]
shearing_matrix = [[1, 0], [3, 1]]
P_sheared = [shearing_matrix[0][0]*P[0]
+ shearing_matrix[0][1]*P[1],
shearing_matrix[1][0]*P[0] +
shearing_matrix[1][1]*P[1]]
print("Sheared point:", P_sheared)
(IV) Reflection through the line y = −x.
P = [4, -2]
reflection_matrix = [[0, -1], [1, 0]]
P_reflected =
[reflection_matrix[0][0]*P[0] +
reflection_matrix[0][1]*P[1],
reflection_matrix[1][0]*P[0] +
reflection_matrix[1][1]*P[1]]
print("Reflected point:", P_reflected)
(ii) Find the combined transformation by using Python program for the following sequence of
transformations:-
(I) Rotation about origin through an angle 60◦.
(II) Scaling in X−coordinate by 7 units.
(III) Uniform scaling by 4 units.
(IV) Reflection through the line y = x..
import math
# Define the point P
P = [4, -2]
# Define the transformation matrices
rotation_matrix = [[math.cos(math.radians(60)), -math.sin(math.radians(60))],
[math.sin(math.radians(60)), math.cos(math.radians(60))]]
scaling_matrix_x = [[7, 0], [0, 1]]
scaling_matrix_uniform = [[4, 0], [0, 4]]
reflection_matrix = [[0, 1], [1, 0]]
# Apply the transformations in sequence
P_rotated = [rotation_matrix[0][0]*P[0] + rotation_matrix[0][1]*P[1],
rotation_matrix[1][0]*P[0] + rotation_matrix[1][1]*P[1]]
P_scaled_x = [scaling_matrix_x[0][0]*P_rotated[0] + scaling_matrix_x[0][1]*P_rotated[1],
scaling_matrix_x[1][0]*P_rotated[0] + scaling_matrix_x[1][1]*P_rotated[1]]
P_scaled_uniform = [scaling_matrix_uniform[0][0]*P_scaled_x[0] + scaling_matrix_uniform[0][1]*P_scaled_x[1],
scaling_matrix_uniform[1][0]*P_scaled_x[0] + scaling_matrix_uniform[1][1]*P_scaled_x[1]]
P_reflected = [reflection_matrix[0][0]*P_scaled_uniform[0] + reflection_matrix[0][1]*P_scaled_uniform[1],
reflection_matrix[1][0]*P_scaled_uniform[0] + reflection_matrix[1][1]*P_scaled_uniform[1]]
print("Combined transformed point:", P_reflected)
12
SAVITRIBAI PHULE PUNE UNIVERSITY, PUNE Board of Studies in Mathematics S.Y.B.Sc (Computer
Science) Practical Examination in Mathematics MTC-243: Python Programming Language-II (CBCS 2019
Pattern)(Semester-IV)
Slip No. : 07
Time: 3 Hours Max. Marks: 35
Q.1 Attempt any TWO of the following. [10]
(a) Plot the graph of f(x) = x4 in [0, 5] with red dashed line with circle markers.
import matplotlib.pyplot as plt
import numpy as np
domain = np.linspace(0, 5, 100)
function_values = domain**4
plt.plot(domain, function_values, 'r--o', label='f(x) = x^4')
plt.title('Graph of f(x) = x^4 in [0, 5]')
plt.xlabel('x')
plt.ylabel('f(x)')
plt.legend()
plt.show()
(b) Using python, generate 3D surface Plot for the function f(x) = sin x 2 + y2 in the interval [0, 10].
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# Create a grid of x and y values
x = np.linspace(0, 10, 100)
y = np.linspace(0, 10, 100)
X, Y = np.meshgrid(x, y)
# Calculate the z values for the function f(x) = sin(x^2) + y^2
Z = np.sin(X**2) + Y**2
# Create a 3D plot
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# Plot the surface
ax.plot_surface(X, Y, Z, cmap='viridis')
# Set labels and title
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('f(x)')
ax.set_title('3D Surface Plot of f(x) = sin(x^2) + y^2')
# Show the plot
plt.show()
(c) Write a python program to draw rectangle with vertices [1, 0], [2, 1], [1, 2] and [0, 1], its rotation
about the origin by π2 radians.
import pygame
import math
# Initialize Pygame
pygame.init()
# Set up some constants
WIDTH, HEIGHT = 640, 480
WHITE = (255, 255, 255)
RED = (255, 0, 0)
# Create the display surface
screen = pygame.display.set_mode((WIDTH, HEIGHT))
# Define the vertices of the rectangle
vertices = [(1, 0), (2, 1), (1, 2), (0, 1)]
# Rotate the vertices by pi/2 radians around the origin
center = (0, 0)
for i in range(len(vertices)):
x, y = vertices[i]
x_new = y - center[1]
y_new = -x + center[0]
vertices[i] = (x_new, y_new)
# Draw the rotated rectangle
pygame.draw.polygon(screen, RED, vertices)
# Flip the display
pygame.display.flip()
# Run until the user asks to quit
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Done! Time to quit.
pygame.quit()
Q.2 Attempt any TWO of the following. [10]
(a) Write a Python program to reflect the line segment joining the points A[5, 3] & B[1, 4] through
the line y = x + 1.
import math
# Define the points A and B
A = (5, 3)
B = (1, 4)
# Define the slope of the line y = x + 1
m=1
# Calculate the intercept of the line y = x + 1
b=1
# Calculate the slope of the line segment AB
m_AB = (B[1] - A[1]) / (B[0] - A[0])
# Calculate the midpoint of the line segment AB
C = ((A[0] + B[0]) / 2, (A[1] + B[1]) / 2)
# Reflect the midpoint C through the line y = x + 1
C_reflected = (C[1] - (C[0] - b) / m, C[0] + (C[1] - b) / m)
# Calculate the slope of the reflected line segment
m_reflected = (C_reflected[1] - C[1]) / (C_reflected[0] - C[0])
# Calculate the intercept of the reflected line segment
b_reflected = C_reflected[1] - m_reflected * C_reflected[0]
# Calculate the reflected points D and E
D = ((C[0] + C_reflected[0]) / 2, (C[1] + C_reflected[1]) / 2)
E = (2 * D[0] - A[0], 2 * D[1] - A[1])
# Print the reflected points
print("The reflected points are D =", D, "and E =", E)
(b) Using sympy declare the points P (5, 2), Q(5, −2), R(5, 0), check whether these points are
collinear. Declare the ray passing through the points P and Q, find the length of this ray between
P and Q. Also find slope of this ray.
import sympy as sp
# Declare the points P, Q, and R
P = sp.Point(5, 2)
Q = sp.Point(5, -2)
R = sp.Point(5, 0)
# Check if the points are collinear
if P.is_collinear(Q, R):
print("The points P, Q, and R are collinear.")
else:
print("The points P, Q, and R are not collinear.")
# Declare the ray passing through points P and Q
ray = sp.Ray(P, Q)
# Find the length of the ray between P and Q
length = ray.length
print("The length of the ray between P and Q is:", length)
# Find the slope of the ray passing through points P and Q
slope = (Q.y - P.y) / (Q.x - P.x)
print("The slope of the ray passing through points P and Q is:", slope)
(c) Write a Python program in 3D to rotate the point (1, 0, 0) through X Plane in anticlockwise
direction (Rotation through Z axis) by an angle of 90◦.
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# Define the point
point = np.array([1, 0, 0])
# Define the rotation matrix
angle = np.pi / 2 # 90 degrees in radians
rotation_matrix = np.array([[1, 0, 0],
[0, np.cos(angle), -np.sin(angle)],
[0, np.sin(angle), np.cos(angle)]])
# Rotate the point
rotated_point = np.dot(rotation_matrix, point)
# Define the X, Y, and Z ranges for the plot
X = np.linspace(-1, 3, 100)
Y = np.linspace(-1, 3, 100)
Z = np.linspace(-1, 3, 100)
# Create a 3D plot
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# Plot the X, Y, and Z axes
ax.plot([0, 1], [0, 0], [0, 0], 'r-', label='X-axis')
ax.plot([0, 0], [0, 1], [0, 0], 'g-', label='Y-axis')
ax.plot([0, 0], [0, 0], [0, 1], 'b-', label='Z-axis')
# Plot the original point
ax.scatter(point[0], point[1], point[2], color='red', marker='o', label='Original point')
# Plot the rotated point
ax.scatter(rotated_point[0], rotated_point[1], rotated_point[2], color='blue', marker='o',
label='Rotated point')
# Set the axis labels and legend
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
ax.legend()
# Show the plot
plt.show()
Q.3 Attempt the following.
(a) Attempt any ONE of the following. [7]
(i) Write a Python program to solve the following LPP:
Min Z = 3.5x + 2y
subject to x + y ≥ 5
x≥4
y≤2
x ≥ 0, y ≥ 0.
import numpy as np
from scipy.optimize import linprog
# Define the objective function coefficients
c = np.array([3.5, 2])
# Define the constraints
A_ub = np.array([[1, 1], [1, 0], [0, 1], [-1, 0], [0, -1]])
b_ub = np.array([5, 4, 2, 0, 0])
# Define the bounds for the variables
bounds = [(0, None), (0, None)]
# Define the options for the linprog function
options = {'disp': True}
# Call the linprog function to solve the LPP
res = linprog(c=c, A_ub=A_ub, b_ub=b_ub, bounds=bounds, options=options)
# Print the solution
print("Solution:")
print("x =", res.x[0])
print("y =", res.x[1])
print("Minimum value of Z =", res.fun)
(ii) Write a python program to display the following LPP by using pulp module and simplex
method. Find its optimal solution if exist.
Max Z = x + 2y + z
subject to x + 2y + 2z ≤ 1
3x + 2y + z ≥ 8
x ≥ 0, y ≥ 0, z ≥ 0.
import pulp
# Define the problem
prob = pulp.LpProblem("LPP", pulp.LpMaximize)
# Define the decision variables
x = pulp.LpVariable("x", 0, None, pulp.LpContinuous)
y = pulp.LpVariable("y", 0, None, pulp.LpContinuous)
z = pulp.LpVariable("z", 0, None, pulp.LpContinuous)
# Define the objective function
prob += x + 2*y + z
# Define the constraints
prob += x + 2*y + 2*z <= 1
prob += 3*x + 2*y + z >= 8
# Solve the problem using the Simplex method
prob.solve()
# Print the solution
print("Status:", pulp.LpStatus[prob.status])
print("Optimal solution:")
print("x =", pulp.value(x))
print("y =", pulp.value(y))
print("z =", pulp.value(z))
print("Maximum value of Z =", pulp.value(prob.objective))
13
(b) Attempt any ONE of the following. [8]
(i) Apply Python program in each of the following transformations on the point P [4, −2]
(I) Refection through Y−axis.
(II) Scaling in X−coordinate by factor 5.
(III) Rotation about origin through an angle π2
. (IV) Shearing in X direction by 72 units.
import math
# Define the point P
P = [4, -2]
# Transformation I: Reflection through Y-axis
P_reflected = [-P[0], P[1]]
print("Point after reflection through Y-axis:",
P_reflected)
# Transformation II: Scaling in X-coordinate by
factor 5
P_scaled = [P[0]*5, P[1]]
print("Point after scaling in X-coordinate by
factor 5:", P_scaled)
# Transformation III: Rotation about origin
through an angle π/2
theta = math.pi/2
P_rotated = [P[0]*math.cos(theta) -
P[1]*math.sin(theta), P[0]*math.sin(theta) +
P[1]*math.cos(theta)]
print("Point after rotation about origin through
an angle π/2:", P_rotated)
# Transformation IV: Shearing in X direction by
72 units
P_sheared = [P[0] + 72*P[1], P[1]]
print("Point after shearing in X direction by 72
units:", P_sheared)
(ii) Find the combined transformation of the line segment between the points A[7, −2] & B[6, 2]
by using Python program for the following sequence of transformations:-
(I) Rotation about origin through an angle π3 .
(II) Scaling in X− coordinate by 7 units.
(III) Uniform scaling by −4 units.
(IV) Reflection through the line X− axis.
import math
# Define the points A and B
A = [7, -2]
B = [6, 2]
# Transformation I: Rotation about origin through an angle π/3
theta = math.pi/3
A_rotated = [A[0]*math.cos(theta) - A[1]*math.sin(theta), A[0]*math.sin(theta) +
A[1]*math.cos(theta)]
B_rotated = [B[0]*math.cos(theta) - B[1]*math.sin(theta), B[0]*math.sin(theta) +
B[1]*math.cos(theta)]
# Transformation II: Scaling in X-coordinate by 7 units
A_scaled = [A_rotated[0]*7, A_rotated[1]]
B_scaled = [B_rotated[0]*7, B_rotated[1]]
# Transformation III: Uniform scaling by -4 units
A_uniform_scaled = [-4*A_scaled[0], -4*A_scaled[1]]
B_uniform_scaled = [-4*B_scaled[0], -4*B_scaled[1]]
# Transformation IV: Reflection through the X-axis
A_reflected = [A_uniform_scaled[0], -A_uniform_scaled[1]]
B_reflected = [B_uniform_scaled[0], -B_uniform_scaled[1]]
# Print the transformed line segment
print("Transformed line segment:", [A_reflected, B_reflected])
14
SAVITRIBAI PHULE PUNE UNIVERSITY, PUNE Board of Studies in Mathematics S.Y.B.Sc (Computer
Science) Practical Examination in Mathematics MTC-243: Python Programming Language-II (CBCS 2019
Pattern)(Semester-IV)
Slip No. : 08
Time: 3 Hours Max. Marks: 35
Q.1 Attempt any TWO of the following. [10]
(a) Plot the graphs of sin x, cos x, ex and x2 in [0, 5] in one figure with (2 × 2) subplots.
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 5, 100)
fig, axs = plt.subplots(2, 2)
axs[0, 0].plot(x, np.sin(x))
axs[0, 0].set_title('sin(x)')
axs[0, 1].plot(x, np.cos(x))
axs[0, 1].set_title('cos(x)')
axs[1, 0].plot(x, np.exp(x))
axs[1, 0].set_title('e^x')
axs[1, 1].plot(x, x**2)
axs[1, 1].set_title('x^2')
plt.show()
(b) Using Python plot the graph of function f(x) = cos(x) in the interval [0, 2π].
import numpy as np
import matplotlib.pyplot as plt
# Define the function
def f(x):
return np.cos(x)
# Define the interval
x = np.linspace(0, 2 * np.pi, 100)
# Plot the graph
plt.plot(x, f(x))
plt.xlabel('x')
plt.ylabel('f(x)')
plt.title('Graph of f(x) = cos(x) in [0, 2π]')
plt.grid(True)
plt.show()
(c) Write a Python program to generate 3D plot of the functions z = sin x + cos y in −10 < x, y < 10.
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# Define the function
def f(x, y):
return np.sin(x) + np.cos(y)
# Define the interval
x = np.linspace(-10, 10, 100)
y = np.linspace(-10, 10, 100)
X, Y = np.meshgrid(x, y)
# Create the 3D plot
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(X, Y, f(X, Y), cmap='viridis')
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')
ax.set_title('3D Plot of z = sin(x) + cos(y) in -10 < x, y < 10')
plt.show()
Q.2 Attempt any TWO of the following. [10]
(a) Write a Python program in 3D to rotate the point (1, 0, 0) through XZ Plane in anticlockwise
direction (Rotation through Y axis) by an angle of 90◦.
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from scipy.spatial.transform import Rotation as R
# Define the point
point = np.array([1, 0, 0])
# Define the rotation
angle = np.pi / 2 # 90 degrees
axis = [0, 1, 0] # Y-axis
# Create the rotation object
r = R.from_rotvec(angle * np.array(axis))
# Rotate the point
rotated_point = r.apply(point)
# Create the 3D plot
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# Plot the original point
ax.scatter(*point, color='red', label='Original Point')
# Plot the rotated point
ax.scatter(*rotated_point, color='blue', label='Rotated Point')
# Add labels and title
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
ax.set_title('Rotation of Point through XZ Plane (Y-axis)')
ax.legend()
# Show the plot
plt.show()
(b) Using python, generate triangle with vertices (0, 0), (4, 0), (1, 4), check whether the triangle is
Scalene triangle.
import matplotlib.pyplot as plt
# Define the vertices of the triangle
vertices = [(0, 0), (4, 0), (1, 4)]
# Plot the triangle
plt.figure()
plt.plot(*vertices, 'bo-')
plt.title('Triangle with vertices (0, 0), (4, 0), (1, 4)')
plt.xlabel('x')
plt.ylabel('y')
plt.show()
# Calculate the lengths of the sides
sides = [((vertices[i][0] - vertices[j][0])**2 + (vertices[i][1] - vertices[j][1])**2)**0.5 for i in range(3)
for j in range(3) if i != j]
# Check if the triangle is scalene
if len(set(sides)) == 3:
print("The triangle is a scalene triangle.")
else:
print("The triangle is not a scalene triangle.")
(c) Write a Python program to find the area and perimeter of the ∆ABC, where A[0, 0], B[6, 0], C[4, 4].
import math
# Define the vertices of the triangle
A = (0, 0)
B = (6, 0)
C = (4, 4)
# Calculate the lengths of the sides
a = math.dist(A, B)
b = math.dist(B, C)
c = math.dist(C, A)
# Calculate the semi-perimeter
s = (a + b + c) / 2
# Calculate the area
area = math.sqrt(s * (s - a) * (s - b) * (s - c))
# Calculate the perimeter
perimeter = a + b + c
# Print the results
print("Area of the triangle: {:.2f}".format(area))
print("Perimeter of the triangle: {:.2f}".format(perimeter))
Q.3 Attempt the following.
(a) Attempt any ONE of the following. [7]
(i) Write a Python program to solve the following LPP:
Max Z = 150x + 75y
subject to 4x + 6y ≤ 24
5x + 3y ≤ 15
x ≥ 0, y ≥ 0.
import pulp as p
# Define the problem
prob = p.LpProblem('Maximize Z', p.LpMaximize)
# Define the decision variables
x = p.LpVariable('x', lowBound=0)
y = p.LpVariable('y', lowBound=0)
# Define the objective function
prob += 150*x + 75*y
# Define the constraints
prob += 4*x + 6*y <= 24
prob += 5*x + 3*y <= 15
# Solve the problem
prob.solve()
# Print the solution
print('Status:', p.LpStatus[prob.status])
print('Optimal value for x:', p.value(x))
print('Optimal value for y:', p.value(y))
print('Optimal value for Z:', p.value(prob.objective))
(ii) Write a python program to display the following LPP by using pulp module and simplex
method. Find its optimal solution if exist.
Max Z = 3x + 5y + 4z
subject to 2x + 3y ≤ 8
2y + 5z ≤ 10
3x + 2y + 4z ≤ 15
x ≥ 0, y ≥ 0, z ≥ 0.
import pulp as p
# Define the problem
prob = p.LpProblem('Maximize Z', p.LpMaximize)
# Define the decision variables
x = p.LpVariable('x', lowBound=0)
y = p.LpVariable('y', lowBound=0)
z = p.LpVariable('z', lowBound=0)
# Define the objective function
prob += 3*x + 5*y + 4*z
# Define the constraints
prob += 2*x + 3*y <= 8
prob += 2*y + 5*z <= 10
prob += 3*x + 2*y + 4*z <= 15
# Solve the problem
prob.solve()
# Print the solution
print('Status:', p.LpStatus[prob.status])
print('Optimal value for x:', p.value(x))
print('Optimal value for y:', p.value(y))
print('Optimal value for z:', p.value(z))
print('Optimal value for Z:', p.value(prob.objective))
15
(b) Attempt any ONE of the following. [8]
(i) Apply Python program in each of the following transformations on the point P [4, −2]
(I) Refection through Y−axis.
P = [4, -2]
P_reflected = [-P[0], P[1]]
print("Reflected point:", P_reflected)
(II) Scaling in X−coordinate by factor 3.
P = [4, -2]
P_scaled = [3*P[0], P[1]]
print("Scaled point:", P_scaled)
(III) Rotation about origin through an angle π.
import math
P = [4, -2]
P_rotated = [-P[0], -P[1]]
print("Rotated point:", P_rotated)
(IV) Shearing in both X and Y direction by −2 and 4 units respectively.
P = [4, -2]
P_sheared = [P[0] - 2*P[1], P[1] + 4*P[0]]
print("Sheared point:", P_sheared)
(ii) Find the combined transformation of the line segment between the points A[4, −1] & B[3, 2]
by using Python program for the following sequence of transformations:-
(I) Rotation about origin through an angle π4 .
(II) Shearing in Y direction by 4 units.
(III) Scaling in X− coordinate by 5 units.
(IV) Reflection through y− axis.
import numpy as np
# Define the points A and B
A = np.array([4, -1])
B = np.array([3, 2])
# Define the transformation matrices
rotation_matrix = np.array([
[np.cos(np.pi/4), -np.sin(np.pi/4)],
[np.sin(np.pi/4), np.cos(np.pi/4)]
])
shearing_matrix = np.array([
[1, 0],
[4, 1]
])
scaling_matrix = np.array([
[5, 0],
[0, 1]
])
reflection_matrix = np.array([
[-1, 0],
[0, 1]
])
# Apply the transformations in sequence
transformed_A =
np.dot(reflection_matrix,
np.dot(scaling_matrix,
np.dot(shearing_matrix,
np.dot(rotation_matrix, A))))
transformed_B =
np.dot(reflection_matrix,
np.dot(scaling_matrix,
np.dot(shearing_matrix,
np.dot(rotation_matrix, B))))
print("Transformed point A:",
transformed_A)
print("Transformed point B:",
transformed_B)
16
SAVITRIBAI PHULE PUNE UNIVERSITY, PUNE Board of Studies in Mathematics S.Y.B.Sc (Computer
Science) Practical Examination in Mathematics MTC-243: Python Programming Language-II (CBCS 2019
Pattern)(Semester-IV)
Slip No. : 09
Time: 3 Hours Max. Marks: 35
Q.1 Attempt any TWO of the following. [10]
(a) Write a python program to Plot 2DX-axis and Y-axis black color and in the same diagram plot
green triangle with vertices [5, 4], [7, 4], [6, 6].
import matplotlib.pyplot as plt
import matplotlib.patches as patches
# Set up the plot
plt.figure(figsize=(6, 6))
plt.xlim(0, 10)
plt.ylim(0, 10)
plt.xlabel('X-axis', color='black')
plt.ylabel('Y-axis', color='black')
plt.xticks(color='black')
plt.yticks(color='black')
# Plot the triangle
triangle = patches.Polygon([(5, 4), (7, 4), (6, 6)], fill=False, color='green')
plt.gca().add_patch(triangle)
# Show the plot
plt.show()
(b) Write a program in python to rotate the point through YZ-plane in anticlockwise direction. (Ro-
tation through Y-axis by an angle of 90◦.)
import numpy as np
# Define the point and the rotation matrix
point = np.array([1, 0, 0])
rotation_matrix = np.array([[np.cos(np.pi/2), 0, np.sin(np.pi/2)],
[0, 1, 0],
[-np.sin(np.pi/2), 0, np.cos(np.pi/2)]])
# Rotate the point
rotated_point = np.dot(rotation_matrix, point)
# Print the original and rotated points
print("Original point: ", point)
print("Rotated point: ", rotated_point)
(c) Using Python plot the graph of function f(x) = cos(x) on the interval [0, 2π].
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 2*np.pi, 100)
y = np.cos(x)
plt.plot(x, y)
plt.show()
Q.2 Attempt any TWO of the following. [10]
(a) Write a python program to rotate the ray by 90◦ having starting point (1, 0) and (2, −1).
def rotate_ray(x, y, angle):
# Convert angle to radians
angle_rad = angle * (3.14159 / 180)
# Calculate new x and y coordinates
new_x = x * math.cos(angle_rad) - y * math.sin(angle_rad)
new_y = x * math.sin(angle_rad) + y * math.cos(angle_rad)
return new_x, new_y
# Starting point (1, 0)
x, y = 1, 0
# Rotate by 90°
new_x, new_y = rotate_ray(x, y, 90)
print("Rotated point:", new_x, new_y)
# Starting point (2, -1)
x, y = 2, -1
# Rotate by 90°
new_x, new_y = rotate_ray(x, y, 90)
print("Rotated point:", new_x, new_y)
(b) Using sympy, declare the points A(0, 7), B(5, 2). Declare the line segment passing through
them. Find the length and midpoint of the line segment passing through points A and B.
import sympy as sp
# Declare points A and B
A = sp.Point(0, 7)
B = sp.Point(5, 2)
# Declare the line segment passing through A and B
AB = sp.Segment(A, B)
# Find the length of the line segment
length = AB.length
print("Length of the line segment:", length)
# Find the midpoint of the line segment
midpoint = AB.midpoint
print("Midpoint of the line segment:", midpoint)
(c) Write a python program to find the area and perimeter of ∆ABC where A(0, 0), B(5, 0), C(3, 3).
import math
# Define the points A, B, and C
A = (0, 0)
B = (5, 0)
C = (3, 3)
# Calculate the lengths of the sides
AB = math.sqrt((B[0] - A[0])**2 + (B[1] - A[1])**2)
BC = math.sqrt((C[0] - B[0])**2 + (C[1] - B[1])**2)
CA = math.sqrt((A[0] - C[0])**2 + (A[1] - C[1])**2)
# Calculate the perimeter
perimeter = AB + BC + CA
# Calculate the semi-perimeter
s = perimeter / 2
# Calculate the area using Heron's formula
area = math.sqrt(s * (s - AB) * (s - BC) * (s - CA))
# Print the results
print("Perimeter:", perimeter)
print("Area:", area)
Q.3 Attempt the following.
(a) Attempt any ONE of the following. [7]
(i) Write a Python program to solve the following LPP:
Max Z = 150x + 75y
subject to 4x + 6y ≤ 24
5x + 3y ≤ 15
x ≥ 0, y ≥ 0.
import numpy as np
from scipy.optimize import linprog
# Define the objective function
c = np.array([150, 75])
# Define the constraints
A_ub = np.array([[4, 6], [5, 3]])
b_ub = np.array([24, 15])
# Define the bounds
bounds = [(0, None), (0, None)]
# Define the options
options = {'disp': True}
# Solve the LPP
res = linprog(c, A_ub=A_ub, b_ub=b_ub, bounds=bounds, options=options)
# Print the results
print("Optimal solution found:")
print("x =", res.x[0])
print("y =", res.x[1])
print("Maximum value of Z =", res.fun)
(ii) Write a python program to display the following LPP by using pulp module and simplex
method. Find its optimal solution if exist.
Max Z = 4x + y + 3z + 5w
subject to 4x + 6y − 5z − 4w ≥ 20
−3x − 2y + 4z + w ≤ 10
−8x − 3y + 3z + 2w ≤ 20
x ≥ 0, y ≥ 0, z ≥ 0, w ≥ 0.
import pulp
# Define the problem
prob = pulp.LpProblem("Maximization Problem", pulp.LpMaximize)
# Define the decision variables
x = pulp.LpVariable("x", 0, None, pulp.LpContinuous)
y = pulp.LpVariable("y", 0, None, pulp.LpContinuous)
z = pulp.LpVariable("z", 0, None, pulp.LpContinuous)
w = pulp.LpVariable("w", 0, None, pulp.LpContinuous)
# Define the objective function
prob += 4*x + y + 3*z + 5*w
# Define the constraints
prob += 4*x + 6*y - 5*z - 4*w >= 20
prob += -3*x - 2*y + 4*z + w <= 10
prob += -8*x - 3*y + 3*z + 2*w <= 20
# Solve the problem using the simplex method
prob.solve()
# Print the optimal solution
print("Optimal solution found:")
print("x =", pulp.value(x))
print("y =", pulp.value(y))
print("z =", pulp.value(z))
print("w =", pulp.value(w))
print("Maximum value of Z =", pulp.value(prob.objective))
17
(b) Attempt any ONE of the following. [8]
(i) Write a python program to apply the following transformations on the point (−2, 4) :
(I) Shearing in Y direction by 7 units.
(II) Scaling in X and Y direction by 72 and 7 units respectively.
(III) Shearing in X and Y direction by 4 and 7 units respectively.
(IV) Rotation about origin by an angle 60◦.
import math
# Define the point
point = [-2, 4]
# Transformation I: Shearing in Y direction by 7 units
point = [point[0], point[1] + 7*point[0]]
# Transformation II: Scaling in X and Y direction by 72 and 7 units respectively
point = [point[0]*72, point[1]*7]
# Transformation III: Shearing in X and Y direction by 4 and 7 units respectively
point = [point[0] + 4*point[1], point[1] + 7*point[0]]
# Transformation IV: Rotation about origin by an angle 60 degrees
angle = math.radians(60)
x = point[0]
y = point[1]
point = [x*math.cos(angle) - y*math.sin(angle), x*math.sin(angle) +
y*math.cos(angle)]
# Print the transformed point
print("Transformed point:", point)
(ii) Write a python program to find the combined transformation of the line segment between
the points A[5, 3] & B[1, 4] for the following sequence of transformations:
(I) Rotate about origin through an angle π2 .
(II) Uniform scaling by −3.5 units.
(III) Scaling in Y− axis by 5 units.
(IV) Shearing in X and Y direction by 3 and 4 units respectively.
import math
# Define the points A and B
A = [5, 3]
B = [1, 4]
# Transformation I: Rotate about origin through an angle π/2
A = [-3, -5]
B = [4, -1]
# Transformation II: Uniform scaling by -3.5 units
A = [-10.5, -17.5]
B = [-3.5, -3.5]
# Transformation III: Scaling in Y-axis by 5 units
A = [-10.5, -87.5]
B = [-3.5, -17.5]
# Transformation IV: Shearing in X and Y direction by 3 and 4 units respectively
A = [(-10.5*3) + (-87.5), (-10.5*4) + (-87.5)]
B = [(-3.5*3) + (-17.5), (-3.5*4) + (-17.5)]
A = [A[0] + 3*A[1], A[1]]
B = [B[0] + 3*B[1], B[1]]
# Print the transformed points A and B
print("Transformed points A and B:", A, B)
18
SAVITRIBAI PHULE PUNE UNIVERSITY, PUNE Board of Studies in Mathematics S.Y.B.Sc (Computer
Science) Practical Examination in Mathematics MTC-243: Python Programming Language-II (CBCS 2019
Pattern)(Semester-IV)
Slip No. : 10
Time: 3 Hours Max. Marks: 35
Q.1 Attempt any TWO of the following. [10]
(a) Write a python program in 3D to rotate the point (1, 0, 0) through XY plane in clockwise direction.
(Rotation through Z-Axis by an angle of 90◦.)
import numpy as np
# Define the point
point = np.array([1, 0, 0])
# Define the rotation matrix for rotation through
Z-axis by 90 degrees
rotation_matrix = np.array([[np.cos(np.pi/2), -
np.sin(np.pi/2), 0],
[np.sin(np.pi/2),
np.cos(np.pi/2), 0],
[0, 0, 1]])
# Rotate the point
rotated_point = np.dot(rotation_matrix, point)
# Print the rotated point
print("Rotated point:", rotated_point)
b)Represent the following information using a bar graph (in green color)
import matplotlib.pyplot as plt
# Define the item labels and expenditure values
items = ['clothing', 'Food', 'rent', 'Petrol', 'Misc.']
expenditures = [600, 4000, 2000, 1500, 700]
# Define the color of the bars
color = 'green'
# Create the bar graph
plt.bar(items, expenditures, color=color)
# Set the title and labels of the graph
plt.title('Expenditure in Rs')
plt.xlabel('Item')
plt.ylabel('Expenditure')
# Show the graph
plt.show()
Item clothing Food rent Petrol Misc.
expenditure in Rs 600 4000 2000 1500 700
(c) Write a python program to plot the 3D line graph whose parametric equation is (cos(2x), sin(2x), x)
for 10 ≤ x ≤ 20 (in red color ), with title to the graph.
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# Define the range of x values
x_values = np.linspace(10, 20, 100)
# Define the parametric equations
x_vals = np.cos(2*x_values)
y_vals = np.sin(2*x_values)
z_vals = x_values
# Create the 3D line graph
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot(x_vals, y_vals, z_vals, color='red')
# Set the title and labels of the graph
ax.set_title('3D Line Graph of (cos(2x), sin(2x), x) for 10
≤ x ≤ 20')
ax.set_xlabel('x-axis')
ax.set_ylabel('y-axis')
ax.set_zlabel('z-axis')
# Show the graph
plt.show()
Q.2 Attempt any TWO of the following. [10]
(a) Write a python program to rotate the ∆ABC by 90◦ where A(1, 1), B(2, −2), C(1, 2).
import numpy as np
# Define the points of the triangle
A = np.array([1, 1])
B = np.array([2, -2])
C = np.array([1, 2])
# Define the rotation matrix
rotation_matrix = np.array([[np.cos(np.pi/2), -np.sin(np.pi/2)],
[np.sin(np.pi/2), np.cos(np.pi/2)]])
# Rotate the points
D = np.dot(rotation_matrix, A)
E = np.dot(rotation_matrix, B)
F = np.dot(rotation_matrix, C)
# Print the rotated points
print("Rotated points:")
print("D:", D)
print("E:", E)
print("F:", F)
(b) Draw a polygon with vertices (0, 0), (2, 0), (2, 3), (1, 6). Write a python program to rotate the
polygon by 180◦.
import matplotlib.pyplot as plt
import numpy as np
# Define the vertices of the polygon
vertices = np.array([[0, 0],
[2, 0],
[2, 3],
[1, 6]])
# Plot the polygon
plt.figure()
plt.plot(vertices[:, 0], vertices[:, 1], 'b-')
plt.title('Original Polygon')
plt.show()
# Define the rotation matrix
rotation_matrix = np.array([[-1, 0],
[0, -1]])
# Rotate the vertices
rotated_vertices = np.dot(rotation_matrix, vertices)
# Plot the rotated polygon
plt.figure()
plt.plot(rotated_vertices[:, 0], rotated_vertices[:, 1], 'r-')
plt.title('Rotated Polygon')
plt.show()
(c) Find the area and perimeter of the ∆ABC, where A[0, 0], B[5, 0], C[3, 3].
import math
# Define the coordinates of the vertices
A = (0, 0)
B = (5, 0)
C = (3, 3)
# Calculate the lengths of the sides
AB = math.sqrt((B[0] - A[0])**2 + (B[1] - A[1])**2)
BC = math.sqrt((C[0] - B[0])**2 + (C[1] - B[1])**2)
CA = math.sqrt((A[0] - C[0])**2 + (A[1] - C[1])**2)
# Calculate the semi-perimeter
s = (AB + BC + CA) / 2
# Calculate the area using Heron's formula
area = math.sqrt(s * (s - AB) * (s - BC) * (s - CA))
# Calculate the perimeter
perimeter = AB + BC + CA
print("The area of the triangle is", area)
print("The perimeter of the triangle is", perimeter)
Q.3 Attempt the following.
(a) Attempt any ONE of the following. [7]
(i) Solve LPP by using python:
Max Z = x + y
subject to x − y ≥ 1
x+y≥2
x ≥ 0, y ≥ 0.
from scipy.optimize import linprog
# Define the coefficients of the objective function
c = [-1, -1] # maximize -Z, so we use -1 instead
of 1
# Define the coefficients of the inequality
constraints
A = [[-1, 1], [-1, -1]] # x - y >= 1, x + y >= 2
b = [-1, -2]
# Define the bounds for the variables
bounds = [(0, None), (0, None)] # x >= 0, y >= 0
# Solve the LPP
res = linprog(c, A_ub=A, b_ub=b,
bounds=bounds, method="highs")
# Print the results
print("Optimal solution:", res.x)
print("Maximum value of Z:", -res.fun) # negate
the result since we minimized -Z
(ii) Write a python program to display the following LPP by using pulp module and simplex
method. Find its optimal solution if exist.
Max Z = 3x + 2y + 5z
subject to x + 2y + z ≤ 430
3x + 4z ≤ 460
x + 4y ≤ 120
x ≥ 0, y ≥ 0, z ≥ 0.
import pulp
# Define the problem
prob = pulp.LpProblem("LPP", pulp.LpMaximize)
# Define the decision variables
x = pulp.LpVariable("x", 0, None, pulp.LpContinuous)
y = pulp.LpVariable("y", 0, None, pulp.LpContinuous)
z = pulp.LpVariable("z", 0, None, pulp.LpContinuous)
# Add the objective function
prob += 3*x + 2*y + 5*z
# Add the constraints
prob += x + 2*y + z <= 430
prob += 3*x + 4*z <= 460
prob += x + 4*y <= 120
# Solve the problem using the simplex method
prob.solve()
# Print the optimal solution
print("Optimal solution:")
print("x =", pulp.value(x))
print("y =", pulp.value(y))
print("z =", pulp.value(z))
print("Maximum value of Z =", pulp.value(prob.objective))
19
(b) Attempt any ONE of the following. [8]
(i) Write a python program to apply the following transformations on the point (−2, 4) :
(I) Refection through X−axis.
(II) Scaling in X−coordinate by factor 6.
(III) Shearing in X direction by 4 units.
(IV) Rotate about origin through an angle 30◦.
import math
# Define the point as a tuple
point = (-2, 4)
# (I) Reflection through X-axis
# Multiply the y-coordinate by -1
point_reflected = (-point[0], -point[1])
print("(I) Reflection through X-axis:", point_reflected)
# (II) Scaling in X-coordinate by factor 6
# Multiply the x-coordinate by 6
point_scaled = (6 * point[0], point[1])
print("(II) Scaling in X-coordinate by factor 6:", point_scaled)
# (III) Shearing in X direction by 4 units
# Add 4 times the x-coordinate to the y-coordinate
point_sheared = (point[0], point[1] + 4 * point[0])
print("(III) Shearing in X direction by 4 units:", point_sheared)
# (IV) Rotate about origin through an angle 30 degrees
# Calculate the new coordinates using trigonometry
angle_in_radians = math.radians(30)
point_rotated = (
point[0] * math.cos(angle_in_radians) - point[1] * math.sin(angle_in_radians),
point[0] * math.sin(angle_in_radians) + point[1] * math.cos(angle_in_radians)
)
print("(IV) Rotate about origin through an angle 30 degrees:", point_rotated)
(ii) Write a python program to find the combined transformation between the points for the
following sequence of transformations:-
(I) Rotation about origin through an angle π2 .
(II) Uniform scaling by 3.5 units.
(III) Scaling in X & Y coordinate by 3 & 5 units respectively.
(IV) Shearing in X direction by 6 units.
import math
# Define the point as a tuple
point = (1, 2)
# Define the transformation functions
def rotate(point, angle):
angle_in_radians = math.radians(angle)
return (
point[0] * math.cos(angle_in_radians) - point[1] * math.sin(angle_in_radians),
point[0] * math.sin(angle_in_radians) + point[1] * math.cos(angle_in_radians)
)
def scale(point, factor):
return (factor * point[0], factor * point[1])
def shear(point, units):
return (point[0], point[1] + units * point[0])
# Apply the transformations
point = rotate(point, math.pi / 2)
point = scale(point, 3.5)
point = scale(point, (3, 5))
point = shear(point, 6)
# Print the transformed point
print("Transformed point:", point)
20
SAVITRIBAI PHULE PUNE UNIVERSITY, PUNE Board of Studies in Mathematics S.Y.B.Sc (Computer
Science) Practical Examination in Mathematics MTC-243: Python Programming Language-II (CBCS 2019
Pattern)(Semester-IV)
Slip No. : 11
Time: 3 Hours Max. Marks: 35
Q.1 Attempt any TWO of the following. [10]
(a) Write a python program to plot 3D axes with labels as X−axis, Y−axis and Z−axis and also plot
following point with given coordinates in the same graph: (70, −25, 15) as a diamond in black
colour.
import matplotlib.pyplot as plt
import numpy as np
# Create a 3D plot
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# Plot the axes with labels
ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')
ax.set_zlabel('Z-axis')
# Plot the point as a diamond in black color
point = (70, -25, 15)
ax.scatter(point[0], point[1], point[2], marker='D', color='black')
# Show the plot
plt.show()
(b) Plot the graph of y = e−x2 in [−5, 5] with red dashed-points line with Upward Pointing triangle.
import matplotlib.pyplot as plt
import numpy as np
# Create a range of x values from -5 to 5
x = np.linspace(-5, 5, 1000)
# Calculate the corresponding y values
y = np.exp(-x**2)
# Create a figure and a set of subplots
fig, ax = plt.subplots()
# Plot the graph with red dashed-points line with upward pointing triangles
ax.plot(x, y, linestyle='--', marker='^', markersize=5, color='red', label='y = e^(-x^2)')
# Set the x and y axis limits
ax.set_xlim([-5, 5])
ax.set_ylim([0, 1.5])
# Add a legend
ax.legend()
# Show the plot
plt.show()
(c) Draw a bar graph in GREEN colour to represent the data below:
Subject Maths Science English Marathi Hindi
Percentage of passing 68 90 70 85 91
import matplotlib.pyplot as plt
# Data
subjects = ['Maths', 'Science', 'English',
'Marathi', 'Hindi']
percentages = [68, 90, 70, 85, 91]
# Create a figure and a set of subplots
fig, ax = plt.subplots()
# Plot the bar chart with green color
ax.bar(subjects, percentages, color='green')
# Set the title and labels
ax.set_title('Percentage of Passing in
Different Subjects')
ax.set_xlabel('Subjects')
ax.set_ylabel('Percentage')
# Show the plot
plt.show()
Q.2 Attempt any TWO of the following. [10]
(a) Write a python program to reflect the ∆ABC through the line y = 3 where A(1, 0), B(2, −1), C(−1, 3).
import matplotlib.pyplot as plt
# Given points of the triangle
A = (1, 0)
B = (2, -1)
C = (-1, 3)
# Reflect the points across the line y = 3
A_reflected = (A[0], 3 - A[1])
B_reflected = (B[0], 3 - B[1])
C_reflected = (C[0], 3 - C[1])
# Plot the original triangle
plt.plot(*zip(A, B, C, A), 'b-')
plt.scatter(*A, color='r', marker='o')
plt.scatter(*B, color='g', marker='o')
plt.scatter(*C, color='b', marker='o')
# Plot the reflected triangle
plt.plot(*zip(A_reflected, B_reflected, C_reflected, A_reflected), 'r--')
plt.scatter(*A_reflected, color='r', marker='^')
plt.scatter(*B_reflected, color='g', marker='^')
plt.scatter(*C_reflected, color='b', marker='^')
# Set the axis labels
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Reflected Triangle')
# Show the plot
plt.show()
(b) Write a python program to rotate the ∆ABC by 90◦ where A(1, 2), B(2, −2), C(−1, 2).
import matplotlib.pyplot as plt
# Given points of the triangle
A = (1, 2)
B = (2, -2)
C = (-1, 2)
# Rotate the points by 90 degrees
A_rotated = (-2, -1)
B_rotated = (-2, 2)
C_rotated = (2, 1)
# Plot the original triangle
plt.plot(*zip(A, B, C, A), 'b-')
plt.scatter(*A, color='r', marker='o')
plt.scatter(*B, color='g', marker='o')
plt.scatter(*C, color='b', marker='o')
# Plot the rotated triangle
plt.plot(*zip(A_rotated, B_rotated, C_rotated, A_rotated), 'r--')
plt.scatter(*A_rotated, color='r', marker='^')
plt.scatter(*B_rotated, color='g', marker='^')
plt.scatter(*C_rotated, color='b', marker='^')
# Set the axis labels
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Rotated Triangle')
# Show the plot
plt.show()
(c) Write a python program to draw a polygon with 6 sides and radius 1 centered at (1, 2) and find
its area and perimeter.
import math
import matplotlib.pyplot as plt
# Given parameters
n = 6 # number of sides
r = 1 # radius
x, y = 1, 2 # center of the polygon
# Calculate the vertices of the polygon
vertices = [(x + r * math.cos(2 * math.pi * (i - 1) / n),
y + r * math.sin(2 * math.pi * (i - 1) / n))
for i in range(1, n + 1)]
# Calculate the area of the polygon
area = 0.5 * r * r * n * math.sin(2 * math.pi / n)
# Calculate the perimeter of the polygon
perimeter = n * r * 2
# Plot the polygon
plt.plot(*zip(*vertices), 'b-')
plt.scatter(*vertices, color='r', marker='o')
# Set the axis labels
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Regular Polygon with {} Sides and Radius {}'.format(n, r))
plt.text(x, y, 'Center', color='b', fontsize=12, fontweight='bold')
# Show the plot
plt.show()
# Print the area and perimeter of the polygon
print('Area: {:.2f}'.format(area))
print('Perimeter: {:.2f}'.format(perimeter))
Q.3 Attempt the following.
(a) Attempt any ONE of the following. [7]
(i) Solve LPP by using python:
Min Z = x + y
subject to x ≥ 6
y≥6
x + y ≥ 11
x ≥ 0, y ≥ 0.
import pulp
# Define the problem
prob = pulp.LpProblem('Minimize_x_y', pulp.LpMinimize)
# Define the decision variables
x = pulp.LpVariable('x', cat='Continuous', lowBound=0)
y = pulp.LpVariable('y', cat='Continuous', lowBound=0)
# Define the objective function
prob += x + y, 'Minimize_Z'
# Define the constraints
prob += x >= 6
prob += y >= 6
prob += x + y >= 11
# Solve the problem
prob.solve()
# Print the solution
print('Status:', pulp.LpStatus[prob.status])
print('Optimal value of x:', pulp.value(x))
print('Optimal value of y:', pulp.value(y))
print('Optimal value of Z:', pulp.value(prob.objective))
(ii) Write a program in python to solve the following LPP and to find optimal solution if exists:
Max Z = 3x + 5y + 4z
subject to 2x + 3y ≤ 8
2y + 5z ≤ 10
3x + 2y + 4z ≤ 15
x ≥ 0, y ≥ 0, z ≥ 0.
import pulp as p
# Define the problem
prob = p.LpProblem('Maximize_3x_5y_4z', p.LpMaximize)
# Define the decision variables
x = p.LpVariable('x', cat='Continuous', lowBound=0)
y = p.LpVariable('y', cat='Continuous', lowBound=0)
z = p.LpVariable('z', cat='Continuous', lowBound=0)
# Define the objective function
prob += 3 * x + 5 * y + 4 * z
# Define the constraints
prob += 2 * x + 3 * y <= 8
prob += 2 * y + 5 * z <= 10
prob += 3 * x + 2 * y + 4 * z <= 15
# Solve the problem
prob.solve()
# Print the solution
print('Status:', p.LpStatus[prob.status])
print('Optimal value of x:', p.value(x))
print('Optimal value of y:', p.value(y))
print('Optimal value of z:', p.value(z))
print('Optimal value of Z:', p.value(prob.objective))
21
(b) Attempt any ONE of the following. [8]
(i) Write a python program to apply the following transformations on the point (−2, 4) :
(I) Shearing in Y direction by 7 units.
(II) Scaling in X and Y direction by 32 and 4 units respectively.
(III) Shearing in X and Y direction by 2 and 4 units respectively.
(IV) Rotation about origin by an angle 45◦.
import math
def shearing_y(point, shear_factor):
x, y = point
return (x, y + shear_factor * x)
def scaling(point, scale_x, scale_y):
x, y = point
return (scale_x * x, scale_y * y)
def shearing_xy(point, shear_x_factor, shear_y_factor):
x, y = point
return (x + shear_x_factor * y, y + shear_y_factor * x)
def rotation(point, angle_in_degrees):
x, y = point
angle_in_radians = math.radians(angle_in_degrees)
return (x * math.cos(angle_in_radians) - y *
math.sin(angle_in_radians),
x * math.sin(angle_in_radians) + y *
math.cos(angle_in_radians))
point = (-2, 4)
# Transformation I: Shearing in Y direction by 7 units
transformed_point_I = shearing_y(point, 7)
print("Transformation I: Shearing in Y direction by 7 units: ",
transformed_point_I)
# Transformation II: Scaling in X and Y direction by 32 and 4
units respectively
transformed_point_II = scaling(point, 32, 4)
print("Transformation II: Scaling in X and Y direction by 32 and 4
units respectively: ", transformed_point_II)
# Transformation III: Shearing in X and Y direction by 2 and 4
units respectively
transformed_point_III = shearing_xy(point, 2, 4)
print("Transformation III: Shearing in X and Y direction by 2 and
4 units respectively: ", transformed_point_III)
# Transformation IV: Rotation about origin by an angle 45
degrees
transformed_point_IV = rotation(point, 45)
print("Transformation IV: Rotation about origin by an angle 45
degrees: ", transformed_point_IV)
(ii) Write a python program to find the combined transformation of the line segment between
the points A[3, 2] & B[2, −3] for the following sequence of transformations:-
(I) Rotation about origin through an angle π6 .
(II) Scaling in Y−coordinate by −4 units.
(III) Uniform scaling by −6.4 units. (IV)
Shearing in Y direction by 5 units.
import math
def rotation(point, angle_in_degrees):
x, y = point
angle_in_radians =
math.radians(angle_in_degrees)
return (x *
math.cos(angle_in_radians) - y *
math.sin(angle_in_radians),
x * math.sin(angle_in_radians)
+ y * math.cos(angle_in_radians))
def scaling(point, scale_x, scale_y):
x, y = point
return (scale_x * x, scale_y * y)
def shearing_y(point, shear_factor):
x, y = point
return (x, y + shear_factor * x)
def uniform_scaling(point,
scale_factor):
x, y = point
return (scale_factor * x, scale_factor
* y)
point_A = (3, 2)
point_B = (2, -3)
# Transformation I: Rotation about
origin through an angle π/6
point_A_I = rotation(point_A, math.pi /
6)
point_B_I = rotation(point_B, math.pi /
6)
# Transformation II: Scaling in Y-
coordinate by -4 units
point_A_II = scaling(point_A_I, 1, -4)
point_B_II = scaling(point_B_I, 1, -4)
# Transformation III: Uniform scaling by
-6.4 units
point_A_III =
uniform_scaling(point_A_II, -6.4)
point_B_III =
uniform_scaling(point_B_II, -6.4)
# Transformation IV: Shearing in Y
direction by 5 units
point_A_IV = shearing_y(point_A_III, 5)
point_B_IV = shearing_y(point_B_III, 5)
print("Combined transformation of the
line segment between points A and B:")
print("Point A: ", point_A_IV)
print("Point B: ", point_B_IV)
22
SAVITRIBAI PHULE PUNE UNIVERSITY, PUNE Board of Studies in Mathematics S.Y.B.Sc (Computer
Science) Practical Examination in Mathematics MTC-243: Python Programming Language-II (CBCS 2019
Pattern)(Semester-IV)
Slip No. : 12
Time: 3 Hours Max. Marks: 35
Q.1 Attempt any TWO of the following. [10]
(a) Write a python program to plot the graph of y = x3 + 10x − 5, for x ∈ [−10, 10] in red colour.
import numpy as np
import matplotlib.pyplot as plt
# Define the range of x values
x = np.linspace(-10, 10, 1000)
# Calculate the corresponding y values
y = x**3 + 10*x - 5
# Plot the graph in red color
plt.plot(x, y, color='red')
# Set the x and y axis labels
plt.xlabel('x')
plt.ylabel('y')
# Set the title of the plot
plt.title('y = x^3 + 10x - 5')
# Display the plot
plt.show()
(b) Write a python program in 3D to rotate the point (1, 0, 0) through XZ− plane in clockwise
direction (rotation through Y− axis by an angle of 90◦).
import numpy as np
def rotate_point_y(point, angle_in_radians):
"""
Rotate a point in 3D around the Y-axis in a clockwise direction.
:param point: A numpy array representing the point in 3D space.
:param angle_in_radians: The angle of rotation in radians.
:return: A new numpy array representing the rotated point.
"""
rotation_matrix = np.array([
[np.cos(angle_in_radians), 0, np.sin(angle_in_radians)],
[0, 1, 0],
[-np.sin(angle_in_radians), 0, np.cos(angle_in_radians)]
])
return rotation_matrix.dot(point)
point = np.array([1, 0, 0])
angle_in_degrees = 90
angle_in_radians = np.radians(angle_in_degrees)
rotated_point = rotate_point_y(point, angle_in_radians)
print("Original point: ", point)
print("Rotated point: ", rotated_point)
(c) Using Python plot the graph of function f(x) = x2 on the interval [−2, 2].
import numpy as np
import matplotlib.pyplot as plt
# Define the range of x values
x = np.linspace(-2, 2, 1000)
# Calculate the corresponding y values
y = x**2
# Plot the graph
plt.plot(x, y)
# Set the x and y axis labels
plt.xlabel('x')
plt.ylabel('y')
# Set the title of the plot
plt.title('f(x) = x^2')
# Display the plot
plt.show()
Q.2 Attempt any TWO of the following. [10]
(a) Write a python program to rotate the segment by 180◦ having end points (1, 0) and (2, −1).
import math
def rotate_point(point, angle_in_radians):
"""
Rotate a point in 2D around the origin by a given angle.
:param point: A tuple representing the point in 2D space.
:param angle_in_radians: The angle of rotation in radians.
:return: A new tuple representing the rotated point.
"""
x, y = point
cos_angle = math.cos(angle_in_radians)
sin_angle = math.sin(angle_in_radians)
return (x * cos_angle - y * sin_angle, x * sin_angle + y * cos_angle)
def rotate_segment(point1, point2, angle_in_radians):
"""
Rotate a segment in 2D around the origin by a given angle.
:param point1: A tuple representing the first endpoint of the segment.
:param point2: A tuple representing the second endpoint of the segment.
:param angle_in_radians: The angle of rotation in radians.
:return: Two tuples representing the rotated endpoints of the segment.
"""
point1_rotated = rotate_point(point1, angle_in_radians)
point2_rotated = rotate_point(point2, angle_in_radians)
return point1_rotated, point2_rotated
# Define the endpoints of the segment
point1 = (1, 0)
point2 = (2, -1)
# Define the angle of rotation (180 degrees)
angle_in_degrees = 180
angle_in_radians = math.radians(angle_in_degrees)
# Rotate the segment
rotated_point1, rotated_point2 = rotate_segment(point1, point2, angle_in_radians)
# Print the original and rotated endpoints of the segment
print("Original segment: ", point1, point2)
print("Rotated segment: ", rotated_point1, rotated_point2)
(b) Write a python program to draw a polygon with 8 sides having radius 5 centered at origin and
find its area and perimeter.
import matplotlib.pyplot as plt
import math
# Define the number of sides of the polygon
num_sides = 8
# Define the radius of the polygon
radius = 5
# Calculate the interior angle of the polygon
angle = 360 / num_sides
# Calculate the length of a side of the polygon
side_length = 2 * radius * math.sin(math.radians(angle / 2))
# Calculate the area of the polygon
area = num_sides * (radius ** 2) * math.sin(math.radians(angle)) / 2
# Calculate the perimeter of the polygon
perimeter = num_sides * side_length
# Generate the vertices of the polygon
vertices = [(radius * math.cos(i * math.radians(angle)), radius * math.sin(i *
math.radians(angle))) for i in range(num_sides)]
# Plot the polygon
plt.plot(*zip(*vertices))
plt.gca().set_aspect('equal')
plt.show()
# Print the results
print("Number of sides:", num_sides)
print("Radius:", radius)
print("Interior angle:", angle)
print("Side length:", side_length)
print("Area:", area)
print("Perimeter:", perimeter)
(c) Write a python program to find the area and perimeter of the ∆XY Z, where X(1, 2), Y (2, −2),
Z(−1, 2).
import math
# Define the coordinates of the vertices
x1, y1 = 1, 2
x2, y2 = 2, -2
x3, y3 = -1, 2
# Calculate the lengths of the sides
side_AB = math.sqrt((x2 - x1)**2 + (y2 - y1)**2)
side_BC = math.sqrt((x3 - x2)**2 + (y3 - y2)**2)
side_AC = math.sqrt((x3 - x1)**2 + (y3 - y1)**2)
# Calculate the semi-perimeter
s = (side_AB + side_BC + side_AC) / 2
# Calculate the area using Heron's formula
area = math.sqrt(s * (s - side_AB) * (s - side_BC) * (s - side_AC))
# Calculate the perimeter
perimeter = side_AB + side_BC + side_AC
# Print the results
print("Area:", area)
print("Perimeter:", perimeter)
Q.3 Attempt the following.
(a) Attempt any ONE of the following. [7]
(i) Write a program to solve the following LPP:
Min Z = 3.5x + 2y
subject to x + y ≥ 5
x≥4
y≤2
x ≥ 0, y ≥ 0.
import numpy as np
from scipy.optimize import linprog
# Define the objective function coefficients
c = np.array([3.5, 2])
# Define the constraint inequalities
A_ub = np.array([[1, 1], [1, 0], [0, 1]])
b_ub = np.array([5, 4, 2])
# Define the lower and upper bounds of the variables
lb = np.array([0, 0])
ub = np.array([None, None])
# Define the LPP
LPP = {'c': c, 'A_ub': A_ub, 'b_ub': b_ub, 'lb': lb, 'ub': ub}
# Solve the LPP
res = linprog(c=LPP['c'], A_ub=LPP['A_ub'], b_ub=LPP['b_ub'], bounds=(LPP['lb'], LPP['ub']),
method='simplex')
# Print the results
print("Optimal solution found:")
print("x =", res.x[0])
print("y =", res.x[1])
print("Minimum Z =", res.fun)
(ii) Write a python program to solve LPP and find optimal solution if exists.
Max Z = 3x + 5y + 4z
subject to 2x + 3y ≤ 8
2y + 5z ≤ 10
3x + 2y + 4z ≤ 15
x ≥ 0, y ≥ 0, z ≥ 0.
import numpy as np
from scipy.optimize import linprog
# Define the objective function coefficients
c = np.array([3, 5, 4])
# Define the constraint inequalities
A_ub = np.array([[2, 3, 0], [0, 2, 5], [3, 2, 4]])
b_ub = np.array([8, 10, 15])
# Define the lower and upper bounds of the variables
lb = np.array([0, 0, 0])
ub = np.array([None, None, None])
# Define the LPP
LPP = {'c': c, 'A_ub': A_ub, 'b_ub': b_ub, 'lb': lb, 'ub': ub}
# Solve the LPP
res = linprog(c=LPP['c'], A_ub=LPP['A_ub'], b_ub=LPP['b_ub'], bounds=(LPP['lb'], LPP['ub']), method='simplex')
# Print the results
print("Optimal solution found:")
print("x =", res.x[0])
print("y =", res.x[1])
print("z =", res.x[2])
print("Maximum Z =", res.fun)
23
(b) Attempt any ONE of the following. [8]
(i) Write a python program to apply the following transformations on the point [−2, 4]
(I) Refection through Y− axis.
(II) Scaling in X−coordinate by factor 6.
(III) Scaling in Y−coordinate by factor 4.1.
(IV) Shearing in X direction by 72 units.
import numpy as np
# Define the point
point = np.array([-2, 4])
# Reflection through Y-axis
point = -point[:, 1]
# Scaling in X-coordinate by factor 6
point[:, 0] *= 6
# Scaling in Y-coordinate by factor 4.1
point[:, 1] *= 4.1
# Shearing in X direction by 72 units
point[:, 0] += 72 * point[:, 1]
# Print the transformed point
print(point)
(ii) Write a python program to find the combined transformation on the line segment between
the points A[4, 1] & B[−3, 0] for the following sequence of Transformations:
(I) Rotation about origin through an angle π4 .
(II) Uniform scaling by 7.3 units.
(III) Scaling in X− coordinate by 3 units.
(IV) Shearing in X direction by 12 units.
import numpy as np
# Define the points A and B
A = np.array([4, 1])
B = np.array([-3, 0])
# Define the transformation matrices
R = np.array([[np.cos(np.pi/4), -np.sin(np.pi/4)],
[np.sin(np.pi/4), np.cos(np.pi/4)]])
S1 = np.array([[7.3, 0],
[0, 7.3]])
S2 = np.array([[3, 0],
[0, 1]])
H = np.array([[1, 12],
[0, 1]])
# Apply the transformations
A = np.dot(R, A)
A = np.dot(S1, A)
A = np.dot(S2, A)
A = np.dot(H, A)
B = np.dot(R, B)
B = np.dot(S1, B)
B = np.dot(S2, B)
B = np.dot(H, B)
# Print the transformed points A and B
print("Transformed points A and B are:")
print(A)
print(B)
24
SAVITRIBAI PHULE PUNE UNIVERSITY, PUNE Board of Studies in Mathematics S.Y.B.Sc (Computer
Science) Practical Examination in Mathematics MTC-243: Python Programming Language-II (CBCS 2019
Pattern)(Semester-IV)
Slip No. : 13
Time: 3 Hours Max. Marks: 35
Q.1 Attempt any TWO of the following. [10]
(a) Write a Python program to plot 2D graph of the functions f(x) = x 2 and g(x) = x3 in [−1, 1].
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-1, 1, 100)
plt.plot(x, x**2, label='f(x) = x^2')
plt.plot(x, x**3, label='g(x) = x^3')
plt.title('Graph of f(x) = x^2 and g(x) = x^3 in [-1, 1]')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.grid()
plt.show()
(b) Using Python, plot the surface plot of parabola z = x2 + y2 in −6 < x, y < 6.
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# Define the range of x and y
x = np.linspace(-6, 6, 100)
y = np.linspace(-6, 6, 100)
# Create a meshgrid of x and y
X, Y = np.meshgrid(x, y)
# Define the z values
Z = X**2 + Y**2
# Create a 3D plot
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# Plot the surface
surf = ax.plot_surface(X, Y, Z, cmap='viridis')
# Set the limits of x, y, and z
ax.set_xlim(-6, 6)
ax.set_ylim(-6, 6)
ax.set_zlim(0, 72)
# Set the labels of x, y, and z
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
# Set the title of the plot
ax.set_title('Surface Plot of Parabola z = x^2 + y^2')
# Show the plot
plt.show()
(c) Write a python program to plot the 3D line graph whose parametric equation is (cos(2x), sin(2x),
x) for 10 ≤ x ≤ 20 (in red color ), with title to the graph.
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# Define the range of x
x = np.linspace(10, 20, 100)
# Calculate the corresponding y and z values
y = np.cos(2*x)
z = np.sin(2*x)
# Create a 3D plot
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# Plot the line in red color
ax.plot(y, z, x, color='red')
# Set the title of the graph
ax.set_title('3D Line Graph of (cos(2x), sin(2x), x) for 10 <= x <= 20')
# Set the limits of x, y, and z
ax.set_xlim(-1, 1)
ax.set_ylim(-1, 1)
ax.set_zlim(10, 20)
# Set the labels of x, y, and z
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
# Show the plot
plt.show()
Q.2 Attempt any TWO of the following. [10]
(a) Write a python program to reflect the ∆ABC through the line y = 3 where A(1, 0), B(2, −1), C(−1, 3).
# Define the coordinates of A, B, and C
A = (1, 0)
B = (2, -1)
C = (-1, 3)
# Define the line of reflection y = 3
line = (3, 0)
# Reflect A, B, and C through the line y = 3
def reflect_point(point, line):
slope = -1 / line[0]
intercept = point[1] - slope * point[0]
reflected_x = point[0]
reflected_y = slope * reflected_x + intercept
return (reflected_x, reflected_y)
A_reflected = reflect_point(A, line)
B_reflected = reflect_point(B, line)
C_reflected = reflect_point(C, line)
# Print the coordinates of the reflected points
print("A' =", A_reflected)
print("B' =", B_reflected)
print("C' =", C_reflected)
# Plot the original triangle and the reflected triangle
import matplotlib.pyplot as plt
plt.plot([A[0], B[0], C[0], A[0]], [A[1], B[1], C[1], A[1]], 'b-')
plt.plot([A_reflected[0], B_reflected[0], C_reflected[0], A_reflected[0]], [A_reflected[1], B_reflected[1],
C_reflected[1], A_reflected[1]], 'r-')
plt.xlabel('X')
plt.ylabel('Y')
plt.title('Triangle ABC and its reflection through the line y = 3')
plt.show()
(b) Find the area and perimeter of the ∆ABC, where A[0, 0], B[5, 0], C[3, 3].
# Define the coordinates of A, B, and C
A = (0, 0)
B = (5, 0)
C = (3, 3)
# Calculate the distance between A and B
AB = ((B[0] - A[0])**2 + (B[1] - A[1])**2)**0.5
# Calculate the distance between B and C
BC = ((C[0] - B[0])**2 + (C[1] - B[1])**2)**0.5
# Calculate the distance between C and A
CA = ((A[0] - C[0])**2 + (A[1] - C[1])**2)**0.5
# Calculate the semi-perimeter of the triangle
s = (AB + BC + CA) / 2
# Calculate the area of the triangle using Heron's formula
area = (s*(s-AB)*(s-BC)*(s-CA))**0.5
# Print the area and perimeter of the triangle
print("Area =", area)
print("Perimeter =", AB + BC + CA)
(c) Using sympy declare the points P(5, 2), Q(5, −2), R(5, 0), check whether these points are
collinear. Declare the ray passing through the points P and Q, find the length of this ray between
P and Q. Also find slope of this ray.
from sympy import Point, Line, Segment
# Declare the points
P = Point(5, 2)
Q = Point(5, -2)
R = Point(5, 0)
# Check if the points are collinear
if P.distance(Q) + Q.distance(R) == P.distance(R):
print("The points are collinear.")
else:
print("The points are not collinear.")
# Declare the ray passing through points P and Q
ray = Line(P, Q)
# Find the length of the ray between P and Q
length = P.distance(Q)
print("The length of the ray between P and Q is:", length)
# Find the slope of the ray
slope = ray.slope
print("The slope of the ray is:", slope)
Q.3 Attempt the following.
(a) Attempt any ONE of the following. [7]
(i) Write a Python program to solve the following LPP:
Max Z = 5x + 3y
subject to x + y ≤ 7
2x + 5y ≤ 1
x ≥ 0, y ≥ 0.
import pulp as pp
# Define the problem
prob = pp.LpProblem('Maximize Z', pp.LpMaximize)
# Define the decision variables
x = pp.LpVariable('x', 0, None, pp.LpContinuous)
y = pp.LpVariable('y', 0, None, pp.LpContinuous)
# Define the objective function
prob += 5*x + 3*y
# Define the constraints
prob += x + y <= 7
prob += 2*x + 5*y <= 1
# Solve the problem
prob.solve()
# Print the optimal solution
print('Optimal solution:')
print('x =', pp.value(x))
print('y =', pp.value(y))
print('Z =', pp.value(prob.objective))
(ii) Write a python program to display the following LPP by using pulp module and simplex
method. Find its optimal solution if exist.
Max Z = 3x + 2y + 5z
subject to x + 2y + z ≤ 430
3x + 4z ≤ 460
x + 4y ≤ 120
x ≥ 0, y ≥ 0, z ≥ 0.
import pulp as pp
# Define the problem
prob = pp.LpProblem('Maximize Z', pp.LpMaximize)
# Define the decision variables
x = pp.LpVariable('x', 0, None, pp.LpContinuous)
y = pp.LpVariable('y', 0, None, pp.LpContinuous)
z = pp.LpVariable('z', 0, None, pp.LpContinuous)
# Define the objective function
prob += 3*x + 2*y + 5*z
# Define the constraints
prob += x + 2*y + z <= 430
prob += 3*x + 4*z <= 460
prob += x + 4*y <= 120
# Solve the problem using the simplex method
prob.solve(pp.pulp.COIN_CMD(msg=0))
# Print the optimal solution
print('Optimal solution:')
print('x =', pp.value(x))
print('y =', pp.value(y))
print('z =', pp.value(z))
print('Z =', pp.value(prob.objective))
25
(b) Attempt any ONE of the following. [8]
(i) Write a python program to apply the following transformations on the point (−2, 4) :
(I) Shearing in Y direction by 7 units.
(II) Scaling in X and Y direction by 72 and 7 units respectively.
(III) Shearing in X and Y direction by 4 and 7 units respectively.
(IV) Rotation about origin by an angle 60◦.
import math
# Define the point
point = (-2, 4)
# Transformation I: Shearing in Y direction by 7 units
point_shear_y = (point[0], point[1] + 7*point[0])
# Transformation II: Scaling in X and Y direction by 72 and 7
units respectively
point_scale = (72*point[0], 7*point[1])
# Transformation III: Shearing in X and Y direction by 4 and 7
units respectively
point_shear_xy = (point[0] + 4*point[1], point[1] + 7*point[0])
# Transformation IV: Rotation about origin by an angle 60
degrees
angle_rad = math.radians(60)
point_rotate = (point[0]*math.cos(angle_rad) -
point[1]*math.sin(angle_rad),
point[0]*math.sin(angle_rad) +
point[1]*math.cos(angle_rad))
# Print the transformed points
print('Transformation I: Shearing in Y direction by 7 units:',
point_shear_y)
print('Transformation II: Scaling in X and Y direction by 72 and 7
units respectively:', point_scale)
print('Transformation III: Shearing in X and Y direction by 4 and
7 units respectively:', point_shear_xy)
print('Transformation IV: Rotation about origin by an angle 60
degrees:', point_rotate)
(ii) Write a python program to Plot 2D x-axis and y-axis in black colour. In the same diagram
plot:-
(I) Green triangle with vertices [5, 4], [7, 4], [6, 6].
(II) Blue rectangle with vertices [2, 2], [10, 2], [10, 8], [2, 8].
(III) Red polygon with vertices [6, 2], [10, 4], [8, 7], [4, 8], [2,
4]. (IV) Isosceles triangle with vertices [0, 0], [4, 0], [2, 4].
import matplotlib.pyplot as plt
import matplotlib.patches as patches
# Set up the figure and axis
fig, ax = plt.subplots()
ax.set_xlim(0, 12)
ax.set_ylim(0, 12)
ax.spines['left'].set_color('black')
ax.spines['right'].set_color('none')
ax.spines['bottom'].set_color('black')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
# Plot the shapes
verts_triangle = [(5, 4), (7, 4), (6, 6), (5, 4)]
ax.fill(verts_triangle, color='green', alpha=0.5)
verts_rectangle = [(2, 2), (10, 2), (10, 8), (2, 8), (2, 2)]
ax.fill(verts_rectangle, color='blue', alpha=0.5)
verts_polygon = [(6, 2), (10, 4), (8, 7), (4, 8), (2, 4), (6, 2)]
ax.fill(verts_polygon, color='red', alpha=0.5)
verts_isosceles = [(0, 0), (4, 0), (2, 4), (0, 0)]
ax.fill(verts_isosceles, color='orange', alpha=0.5)
# Show the plot
plt.show()
26
SAVITRIBAI PHULE PUNE UNIVERSITY, PUNE Board of Studies in Mathematics S.Y.B.Sc (Computer
Science) Practical Examination in Mathematics MTC-243: Python Programming Language-II (CBCS 2019
Pattern)(Semester-IV)
Slip No. : 14
Time: 3 Hours Max. Marks: 35
Q.1 Attempt any TWO of the following. [10]
(a) Write a Python program to plot 2D graph of the functions f(x) = x 2 and g(x) = x3 in [−1, 1].
import matplotlib.pyplot as plt
import numpy as np
# Set up the figure and axis
fig, ax = plt.subplots()
ax.set_xlim(-1, 1)
ax.set_ylim(-1, 1)
ax.spines['left'].set_color('black')
ax.spines['right'].set_color('none')
ax.spines['bottom'].set_color('black')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
# Plot the functions
x = np.linspace(-1, 1, 100)
ax.plot(x, x**2, label='f(x) = x^2')
ax.plot(x, x**3, label='g(x) = x^3')
# Add a legend
ax.legend()
# Show the plot
plt.show()
(b) Write a Python program to plot 3D graph of the function f(x) = e−x2 in [−5, 5] with green dashed
points line with upward pointing triangle.
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# Create a range of x values from -5 to 5
x = np.linspace(-5, 5, 100)
# Calculate the corresponding y values using the function f(x) = e^-x^2
y = np.exp(-x**2)
# Create a 3D plot
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# Plot the function with a green dashed line and an upward pointing triangle marker
ax.plot(x, y, np.zeros_like(x), color='green', linestyle='--', marker='^', markersize=5)
# Set the limits of the x, y, and z axes
ax.set_xlim(-5, 5)
ax.set_ylim(0, 1.5)
ax.set_zlim(0, 1.5)
# Set the labels of the x, y, and z axes
ax.set_xlabel('x')
ax.set_ylabel('y = e^-x^2')
ax.set_zlabel('z')
# Show the plot
plt.show()
(c) Write a Python program to generate 3D plot of the function z = sin(x) + cos(y) in −5 < x, y < 5.
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# Create a grid of x and y values
x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
X, Y = np.meshgrid(x, y)
# Calculate the z values on the grid
Z = np.sin(X) + np.cos(Y)
# Create a 3D plot
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# Plot the surface
ax.plot_surface(X, Y, Z, cmap='viridis', edgecolor='none')
# Set the axis labels
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')
# Set the title
ax.set_title('3D Plot of z = sin(x) + cos(y)')
# Show the plot
plt.show()
Q.2 Attempt any TWO of the following. [10]
(a) Write a Python program to reflect the line segment joining the points A[5, 3] and B[1, 4] through
the line y = x + 1.
import matplotlib.pyplot as plt
# Define the given points
A = [5, 3]
B = [1, 4]
# Define the slope and y-intercept of the line y = x + 1
m=1
b=1
# Calculate the reflected points C and D
C = [A[0], 2*A[1] - B[1]]
D = [B[0], 2*B[1] - A[1]]
# Plot the given points, reflected points, and the line y = x + 1
plt.plot([A[0], B[0]], [A[1], B[1]], 'bo')
plt.plot([C[0], D[0]], [C[1], D[1]], 'ro')
plt.plot([-10, 10], [m*(-10) + b, m*(10) + b], 'k-')
plt.xlabel('x')
plt.ylabel('y')
plt.legend(['AB', 'CD', 'y = x + 1'])
plt.show()
(b) Write a Python program to draw a polygon with vertices (0, 0), (2, 0), (2, 3) and (1, 6) and rotate
it by 180o.
import turtle
# Create a new turtle screen
screen = turtle.Screen()
screen.bgcolor("white")
# Create a new turtle object
turtle = turtle.Turtle()
turtle.speed(0)
# Draw the polygon
turtle.penup()
turtle.goto(0, 0)
turtle.pendown()
turtle.begin_fill()
for _ in range(2):
turtle.forward(2)
turtle.right(90)
turtle.forward(3)
turtle.right(90)
turtle.end_fill()
# Rotate the polygon by 180 degrees
turtle.penup()
turtle.goto(0, 0)
turtle.pendown()
turtle.left(180)
turtle.begin_fill()
for _ in range(2):
turtle.forward(2)
turtle.right(90)
turtle.forward(3)
turtle.right(90)
turtle.end_fill()
# Hide the turtle object and close the turtle screen
turtle.hideturtle()
turtle.done()
(c) Write a Python program to find the area and perimeter of the triangle ABC, where A[0, 0], B[5, 0]
and C[3, 3].
import math
# Define the vertices of the triangle
A = [0, 0]
B = [5, 0]
C = [3, 3]
# Calculate the distance between each pair of vertices
AB = math.sqrt((B[0] - A[0])**2 + (B[1] - A[1])**2)
BC = math.sqrt((C[0] - B[0])**2 + (C[1] - B[1])**2)
CA = math.sqrt((A[0] - C[0])**2 + (A[1] - C[1])**2)
# Calculate the semi-perimeter of the triangle
s = (AB + BC + CA) / 2
# Calculate the area of the triangle using Heron's formula
area = math.sqrt(s * (s - AB) * (s - BC) * (s - CA))
# Calculate the perimeter of the triangle
perimeter = AB + BC + CA
# Print the results
print("Area of the triangle:", area)
print("Perimeter of the triangle:", perimeter)
Q.3 Attempt the following.
(a) Attempt any ONE of the following. [7]
i. Write a Python program to solve the following LPP:
Max Z = 150x + 75y
subject to 4x + 6y ≤ 24
5x + 3y ≤ 15
x ≥ 0, y ≥ 0.
import pulp as p
# Define the problem
prob = p.LpProblem('Maximize Z', p.LpMaximize)
# Define the decision variables
x = p.LpVariable('x', 0, None)
y = p.LpVariable('y', 0, None)
# Define the objective function
prob += 150*x + 75*y
# Define the constraints
prob += 4*x + 6*y <= 24
prob += 5*x + 3*y <= 15
# Solve the problem
prob.solve()
# Print the optimal solution
print('Optimal solution:')
print('x =', p.value(x))
print('y =', p.value(y))
print('Z =', p.value(prob.objective))
ii. Write a Python program to solve the following LPP:
Min Z = x + y
subject to x ≥ 6
y≥6
x + y ≤ 11
x ≥ 0, y ≥ 0.
import numpy as np
from scipy.optimize import linprog
# Define the objective function coefficients
obj = np.array([1, 1])
# Define the constraint coefficients
lhs = np.array([[0, -1], [-1, 0], [1, 1]])
# Define the constraint bounds
rhs = np.array([-6, -6, 11])
# Define the variable bounds
bnd = (0, None)
# Define the problem
prob = linprog(c=obj, A_ub=lhs, b_ub=rhs, bounds=bnd, method='simplex')
# Print the results
print('Optimal solution:')
print('x =', prob.x[0])
print('y =', prob.x[1])
print('Z =', prob.fun)
27
(b) Attempt any ONE of the following. [8]
i. Apply each of the following transformations on the point P [2, −3].
I. Reflection through X-axis.
II. Scaling in X-coordinate by factor 2.
III. Scaling in Y-coordinate by factor 1.5.
IV. Reflection through the line y = x.
# Initial point P
P = [2, -3]
print("Initial point P:", P)
# I. Reflection through X-axis
P_refl_x = [P[0], -P[1]]
print("After reflection through X-axis:", P_refl_x)
# II. Scaling in X-coordinate by factor 2
P_scaled_x = [2 * P_refl_x[0], P_refl_x[1]]
print("After scaling in X-coordinate by factor 2:", P_scaled_x)
# III. Scaling in Y-coordinate by factor 1.5
P_scaled_xy = [P_scaled_x[0], 1.5 * P_scaled_x[1]]
print("After scaling in Y-coordinate by factor 1.5:", P_scaled_xy)
# IV. Reflection through the line y = x
P_refl_xy = [P_scaled_xy[1], P_scaled_xy[0]]
print("After reflection through the line y = x:", P_refl_xy)
ii. Apply each of the following transformations on the point P [3, −1].
I. Shearing in Y direction by 2 units.
II. Scaling in X and Y direction by 1/2 and 3 units respectively.
III. Shearing in both X and Y direction by -2 and 4 units respectively.
IV. Rotation about origin by an angle 30 degrees.
# Initial point P
P = [3, -1]
print("Initial point P:", P)
# I. Shearing in Y direction by 2 units
P_sheared_y = [P[0] + 2 * P[1], P[1]]
print("After shearing in Y direction by 2 units:", P_sheared_y)
# II. Scaling in X and Y direction by 1/2 and 3 units respectively
P_scaled = [0.5 * P_sheared_y[0], 3 * P_sheared_y[1]]
print("After scaling in X and Y direction by 1/2 and 3 units respectively:", P_scaled)
# III. Shearing in both X and Y direction by -2 and 4 units respectively
P_sheared_xy = [P_scaled[0] - 2 * P_scaled[1], P_scaled[1] + 4 * P_scaled[0]]
print("After shearing in both X and Y direction by -2 and 4 units respectively:",
P_sheared_xy)
# IV. Rotation about origin by an angle 30 degrees
import math
angle_in_radians = math.radians(30)
P_rotated = [
P_sheared_xy[0] * math.cos(angle_in_radians) - P_sheared_xy[1] *
math.sin(angle_in_radians),
P_sheared_xy[0] * math.sin(angle_in_radians) + P_sheared_xy[1] *
math.cos(angle_in_radians)
]
print("After rotation about origin by an angle 30 degrees:", P_rotated)
28
SAVITRIBAI PHULE PUNE UNIVERSITY, PUNE Board of Studies in Mathematics S.Y.B.Sc (Computer
Science) Practical Examination in Mathematics MTC-243: Python Programming Language-II (CBCS 2019
Pattern)(Semester-IV)
Slip No. : 15
Time: 3 Hours Max. Marks: 35
Q.1 Attempt any TWO of the following. [10]
(a) Write the Python program to find area of the triangle ABC, where A[0, 0], B[5, 0], C[3, 3].
import math
# Coordinates of vertices A, B, and C
A = [0, 0]
B = [5, 0]
C = [3, 3]
# Calculate the length of sides AB, BC, and AC
AB = math.sqrt((B[0] - A[0])**2 + (B[1] - A[1])**2)
BC = math.sqrt((C[0] - B[0])**2 + (C[1] - B[1])**2)
AC = math.sqrt((C[0] - A[0])**2 + (C[1] - A[1])**2)
# Calculate the semi-perimeter of the triangle
s = (AB + BC + AC) / 2
# Calculate the area of the triangle using Heron's formula
area = math.sqrt(s * (s - AB) * (s - BC) * (s - AC))
print(f"The area of the triangle ABC is {area:.2f}")
(b) Write the Python program to plot the graph of the function, using def()
import matplotlib.pyplot as plt
# Define the function
def f(x):
if -10 <= x < 5:
return x**2 + 4
elif 5 <= x < 10:
return 3 * x + 9
else:
return None
# Generate the x values
x = list(range(-10, 11))
# Generate the y values
y = [f(i) for i in x]
# Plot the graph
plt.plot(x, y)
plt.xlabel('x')
plt.ylabel('y')
plt.title('Graph of f(x) = x^2 + 4 if -10 <= x < 5 and f(x) = 3x + 9 if 5 <= x < 10')
plt.grid(True)
plt.show()
f(x) = x2 + 4 if −10 ≤ x < 5
3x + 9 if 5 ≤ x < 10
(c) Write the python program to plot the graphs of sin x, cos x, ex and x2 in [0, 5] in one figure with
2 × 2 subplots.
import matplotlib.pyplot as plt
import numpy as np
# Generate the x values using the
linspace function
x = np.linspace(0, 5, 1000)
# Generate the y values for each
function
sin_y = np.sin(x)
cos_y = np.cos(x)
exp_y = np.exp(x)
x2_y = x**2
# Create the figure and the subplots
fig, axs = plt.subplots(2, 2)
# Plot the graphs on each subplot
axs[0, 0].plot(x, sin_y)
axs[0, 0].set_title('sin(x)')
axs[0, 1].plot(x, cos_y)
axs[0, 1].set_title('cos(x)')
axs[1, 0].plot(x, exp_y)
axs[1, 0].set_title('e^x')
axs[1, 1].plot(x, x2_y)
axs[1, 1].set_title('x^2')
# Add labels and a title to the figure
plt.xlabel('x')
plt.ylabel('y')
plt.suptitle('Graphs of sin(x), cos(x),
e^x, and x^2 in [0, 5]')
# Display the figure
plt.show()
Q.2 Attempt any TWO of the following. [10]
(a) Write the Python program to rotate the triangle ABC by 180 degree, where A[1, 2], B[2, −2] & C[−1, 2].
def rotate_point(point):
return (-point[0], -point[1])
A = [1, 2]
B = [2, -2]
C = [-1, 2]
A_rotated = rotate_point(A)
B_rotated = rotate_point(B)
C_rotated = rotate_point(C)
print("Rotated points:")
print("A:", A_rotated)
print("B:", B_rotated)
print("C:", C_rotated)
(b) Write the Python program to plot the graph of function f(x) = ex in the interval [−10, 10].
import numpy as np
import matplotlib.pyplot as plt
# Define the function
def f(x):
return np.exp(x)
# Generate x values in the interval [-10, 10]
x = np.linspace(-10, 10, 400)
# Calculate the corresponding y values
y = f(x)
# Create the plot
plt.plot(x, y)
# Add title and labels
plt.title("Graph of f(x) = e^x")
plt.xlabel("x")
plt.ylabel("f(x)")
# Show the plot
plt.show()
(c) Write a Python program to plot the 3D graph whose parametric equation is (cos(2x), sin(2x), x)
for 10 ≤ x ≤ 20 (in red color ), with title to the graph.
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
x = np.linspace(10, 20, 100)
y = np.cos(2*x)
z = np.sin(2*x)
ax.plot(y, z, x, color='red', label='Parametric Curve')
ax.set_xlabel('X Axis')
ax.set_ylabel('Y Axis')
ax.set_zlabel('Z Axis')
ax.set_title('Parametric Curve (cos(2x), sin(2x), x) for 10 ≤ x ≤ 20')
ax.legend()
plt.show()
Q.3 Attempt the following.
(a) Attempt any ONE of the following. [7]
i. Write a Python program to solve the following LPP:
Min Z = 3.5x + 2y
subject to x + y ≥ 5
x≥4
y≤2
x ≥ 0, y ≥ 0.
import numpy as np
from scipy.optimize import linprog
# Objective function coefficients
c = np.array([3.5, 2])
# Inequality constraints matrix
A_ub = np.array([[1, 1], [1, 0], [0, -1]])
# Inequality constraints right-hand side
b_ub = np.array([5, 4, -2])
# Bounds on variables
bounds = ((0, None), (0, None))
# Solve the LPP
res = linprog(c, A_ub=A_ub, b_ub=b_ub, bounds=bounds)
# Print the results
print("Optimal solution:")
print("x =", res.x[0])
print("y =", res.x[1])
print("Optimal objective value: Z =", res.fun)
ii. Write a Python program to solve the following LPP:
Min Z = x + y
subject to x ≥ 6
y≥6
x + y ≤ 11
x ≥ 0, y ≥ 0.
import numpy as np
from scipy.optimize import linprog
# Objective function coefficients
c = np.array([1, 1])
# Inequality constraints matrix
A_ub = np.array([[1, 1], [1, 0], [0, 1]])
# Inequality constraints right-hand side
b_ub = np.array([11, 6, 6])
# Bounds on variables
bounds = ((0, None), (0, None))
# Solve the LPP
res = linprog(c, A_ub=A_ub, b_ub=b_ub, bounds=bounds)
# Print the results
print("Optimal solution:")
print("x =", res.x[0])
print("y =", res.x[1])
print("Optimal objective value: Z =", res.fun)
29
(b) Attempt any ONE of the following. [8]
i. Write a Python program to find the combined transformation of the line segment between
the points A[5, 3] and B[1, 4] for the following sequence of transformations:
I. First rotation about origin through an angle π/2.
II. Followed by scaling in x co-ordinate by 5 units.
III. Followed by reflection through the line y = −x.
import numpy as np
# Define the points A and B
A = np.array([5, 3])
B = np.array([1, 4])
# I. Rotation about origin through an angle π/2
theta = np.pi / 2
rotation_matrix = np.array([[np.cos(theta), -np.sin(theta)],
[np.sin(theta), np.cos(theta)]])
A_rotated = np.dot(rotation_matrix, A)
B_rotated = np.dot(rotation_matrix, B)
# II. Scaling in x co-ordinate by 5 units
scaling_matrix = np.array([[5, 0],
[0, 1]])
A_scaled = np.dot(scaling_matrix, A_rotated)
B_scaled = np.dot(scaling_matrix, B_rotated)
# III. Reflection through the line y = -x
reflection_matrix = np.array([[0, -1],
[-1, 0]])
A_reflected = np.dot(reflection_matrix, A_scaled)
B_reflected = np.dot(reflection_matrix, B_scaled)
# Print the transformed points
print("Transformed points:")
print("A: ", A_reflected)
print("B: ", B_reflected)
ii. Write a Python program to apply each of the following transformations on the point P [−2, 4].
I. Reflection through the line y = x + 1.
II. Scaling in Y -coordinate by factor 1.5.
III. Shearing in X direction by 2 units.
IV. Rotation about origin by an angle 45 degrees.
# Define the point P
P = np.array([-2, 4])
# I. Reflection through the line y = x + 1
reflection_matrix = np.array([[1, 1],
[1, 0]])
P_reflected = np.dot(reflection_matrix, P)
# II. Scaling in Y-coordinate by factor 1.5
scaling_matrix = np.array([[1, 0],
[0, 1.5]])
P_scaled = np.dot(scaling_matrix, P)
# III. Shearing in X direction by 2 units
shearing_matrix = np.array([[1, 2],
[0, 1]])
P_sheared = np.dot(shearing_matrix, P)
# IV. Rotation about origin by an angle 45 degrees
rotation_matrix = np.array([[np.cos(np.pi/4), -np.sin(np.pi/4)],
[np.sin(np.pi/4), np.cos(np.pi/4)]])
P_rotated = np.dot(rotation_matrix, P)
# Print the transformed points
print("Reflection through y = x + 1: ", P_reflected)
print("Scaling in Y-coordinate by 1.5: ", P_scaled)
print("Shearing in X direction by 2 units: ", P_sheared)
print("Rotation about origin by 45 degrees: ", P_rotated)
30
SAVITRIBAI PHULE PUNE UNIVERSITY, PUNE Board of Studies in Mathematics S.Y.B.Sc (Computer
Science) Practical Examination in Mathematics MTC-243: Python Programming Language-II (CBCS 2019
Pattern)(Semester-IV)
Slip No. : 16
Time: 3 Hours Max. Marks: 35
Q.1 Attempt any TWO of the following. [10]
(a) Write a Python program to plot graph of the function f(x, y) = –x2 − y2 when −10 ≤ x, y ≤ 10.
import numpy as np
import matplotlib.pyplot as plt
# Define the function f(x, y)
f = lambda x, y: -x**2 - y**2
# Create a meshgrid of x and y values
x = np.linspace(-10, 10, 100)
y = np.linspace(-10, 10, 100)
X, Y = np.meshgrid(x, y)
# Evaluate the function at each point in the meshgrid
Z = f(X, Y)
# Create a 3D plot of the function
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(X, Y, Z, cmap='coolwarm')
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
ax.set_title('Graph of f(x, y) = -x^2 - y^2')
# Show the plot
plt.show()
(b) Write a Python program to plot graph of the function f(x) = log(3x 2), in [1, 10] with black dashed
points.
import numpy as np
import matplotlib.pyplot as plt
# Define the function f(x)
f = lambda x: np.log(3*x**2)
# Create an array of x values in the interval [1, 10]
x = np.linspace(1, 10, 100)
# Evaluate the function at each x value
y = f(x)
# Create a plot of the function with black dashed points
plt.plot(x, y, 'k--')
# Set the x and y axis labels and title
plt.xlabel('x')
plt.ylabel('f(x)')
plt.title('Graph of f(x) = log(3x^2) in [1, 10]')
# Show the plot
plt.show()
(c) Write a Python program to generate plot of the function f(x) = x 2, in the interval [−5, 5], in figure
of size 6 × 6 inches.
import numpy as np
import matplotlib.pyplot as plt
# Define the function f(x)
f = lambda x: x**2
# Create an array of x values in the interval [-5, 5]
x = np.linspace(-5, 5, 100)
# Evaluate the function at each x value
y = f(x)
# Create a plot of the function with a 6 x 6 inch figure size
plt.figure(figsize=(6, 6))
plt.plot(x, y)
# Set the x and y axis labels and title
plt.xlabel('x')
plt.ylabel('f(x)')
plt.title('Graph of f(x) = x^2 in [-5, 5]')
# Show the plot
plt.show()
Q.2 Attempt any TWO of the following. [10]
(a) Write a Python program to declare the line segment passing through the points A(0, 7), B(5, 2).
Also find the length and midpoint of the line segment passing through points A and B.
# Define the coordinates of points A and B
A = (0, 7)
B = (5, 2)
# Calculate the length of the line segment AB
import math
ab_length = math.sqrt((B[0] - A[0])**2 + (B[1] - A[1])**2)
# Calculate the midpoint of the line segment AB
midpoint = ((A[0] + B[0])/2, (A[1] + B[1])/2)
# Print the results
print("The line segment passing through the points A and B is defined by the following pairs:")
print(f"A = {A}")
print(f"B = {B}")
print(f"\nThe length of the line segment AB is: {ab_length:.2f}")
print(f"\nThe midpoint of the line segment AB is: {midpoint}")
(b) Write a Python program to draw a polygon with vertices (0, 0), (2, 0), (2, 3) and (1, 6) and rotate
it by 90o.
import turtle
# Create a new turtle screen and set its background color
screen = turtle.Screen()
screen.bgcolor("white")
# Create a new turtle object
my_turtle = turtle.Turtle()
my_turtle.color("black")
# Draw the polygon
my_turtle.penup()
my_turtle.goto(0, 0)
my_turtle.pendown()
my_turtle.begin_fill()
my_turtle.goto(2, 0)
my_turtle.goto(2, 3)
my_turtle.goto(1, 6)
my_turtle.goto(0, 0)
my_turtle.end_fill()
# Rotate the polygon by 90 degrees
my_turtle.penup()
my_turtle.goto(0, 0)
my_turtle.pendown()
my_turtle.left(90)
# Hide the turtle
my_turtle.hideturtle()
# Keep the window open
turtle.done()
(c) Write a Python program to Generate vector x in the interval [0, 15] using numpy package with
100 subintervals.
import numpy as np
# Generate the vector x with 100 subintervals in the interval [0, 15]
x = np.linspace(0, 15, 100)
# Print the vector x
print(x)
Q.3 Attempt the following.
(a) Attempt any ONE of the following. [7]
i Write a Python program to solve the following LPP:
Max Z = 5x + 3y
subject to 3x + 5y ≤ 15
6x + 2y ≥ 24
x ≥ 0, y ≥ 0.
import numpy as np
from scipy.optimize import linprog
# Define the objective function coefficients
c = np.array([5, 3])
# Define the constraint coefficients
A_ub = np.array([[3, 5], [6, 2], [1, 0]])
b_ub = np.array([15, 24, 0])
# Define the lower and upper bounds of the variables
lb = np.array([0, 0])
ub = np.array([np.inf, np.inf])
# Define the options for the linprog function
options = {}
# Call the linprog function to solve the LPP
res = linprog(c, A_ub=A_ub, b_ub=b_ub, bounds=(lb, ub), options=options)
# Print the solution
print("Solution:")
print("x =", res.x[0])
print("y =", res.x[1])
print("Maximum value of Z =", res.fun)
ii Write a Python program to solve the following LPP:
Min Z = 3.5x + 2y
subject to x + y ≥ 5
x≥4
y≤2
x ≥ 0, y ≥ 0.
import numpy as np
from scipy.optimize import linprog
# Define the objective function coefficients
c = np.array([3.5, 2])
# Define the constraint coefficients
A_ub = np.array([[1, 1], [1, 0], [0, 1]])
b_ub = np.array([5, 4, 2])
# Define the lower and upper bounds of the variables
lb = np.array([0, 0])
ub = np.array([np.inf, 2])
# Define the options for the linprog function
options = {}
# Call the linprog function to solve the LPP
res = linprog(c, A_eq=A_ub, b_eq=b_ub, bounds=(lb, ub), options=options)
# Print the solution
print("Solution:")
print("x =", res.x[0])
print("y =", res.x[1])
print("Minimum value of Z =", res.fun)
(b) Attempt any ONE of the following. [8]
i. Write a python program to plot the Triangle with vertices at [4, 3], [6, 3], [6, 5]. and its reflec-
tions through, 1) x-axis, 2) y-axis. All the figures must be in different colors, also plot the two
axes.
import matplotlib.pyplot as plt
# Define the vertices of the triangle
vertices = [(4, 3), (6, 3), (6, 5)]
# Define the colors for the original triangle and its reflections
colors = ['b', 'g', 'r', 'y', 'c']
# Plot the original triangle
plt.plot(*zip(*vertices), 'o-', color=colors[0], label='Original Triangle')
# Plot the reflections
reflections = [
[(x, y) for x, y in vertices], # x-axis reflection
[(x, -y) for x, y in vertices], # y-axis reflection
]
for i, reflection in enumerate(reflections):
plt.plot(*zip(*reflection), 'o-', color=colors[i+1], label=f'Reflection {["x-axis", "y-axis"][i]}')
# Plot the x and y axes
plt.axhline(0, color='k', linestyle='-')
plt.axvline(0, color='k', linestyle='-')
# Add a legend
plt.legend()
# Show the plot
plt.show()
ii. Write a python program to plot the Triangle with vertices at [3, 3], [3, 6], [0, 6] and its
reflections through, line y = x and y-axis. Also plot the mirror lines.
import matplotlib.pyplot as plt
import numpy as np
# Define the vertices of the triangle
vertices = [(3, 3), (3, 6), (0, 6)]
# Define the colors for the original triangle and its reflections
colors = ['b', 'g', 'r', 'y', 'c']
# Plot the original triangle
plt.plot(*zip(*vertices), 'o-', color=colors[0], label='Original Triangle')
# Plot the reflections
reflections = [
[(y, x) for x, y in vertices], # Reflection through y = x
[(x, -y) for x, y in vertices], # Reflection through y-axis
]
for i, reflection in enumerate(reflections):
plt.plot(*zip(*reflection), 'o-', color=colors[i+1], label=f'Reflection {["y = x", "y-axis"][i]}')
# Plot the mirror lines
plt.plot(np.arange(0, 7, 0.1), np.arange(0, 7, 0.1), 'k--', label='y = x')
plt.axvline(0, color='k', linestyle='-')
# Add a legend
plt.legend()
# Show the plot
plt.show()
31
SAVITRIBAI PHULE PUNE UNIVERSITY, PUNE Board of Studies in Mathematics S.Y.B.Sc (Computer
Science) Practical Examination in Mathematics MTC-243: Python Programming Language-II (CBCS 2019
Pattern)(Semester-IV)
Slip No. : 17
Time: 3 Hours Max. Marks: 35
Q.1 Attempt any TWO of the following. [10]
(a) Write a python program to plot the 3D graph of the function z = x 2 + y2 in −6 < x, y < 6 using
surface plot.
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# Create a grid of x and y values
x = np.linspace(-6, 6, 100)
y = np.linspace(-6, 6, 100)
X, Y = np.meshgrid(x, y)
# Calculate the z values for each point on the grid
Z = X**2 + Y**2
# Create a 3D plot
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# Plot the surface
ax.plot_surface(X, Y, Z, cmap='viridis')
# Set the axis labels
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
# Set the title
ax.set_title('3D Surface Plot of z = x^2 + y^2')
# Show the plot
plt.show()
(b) Write a python program to plot 3D contours for the function f(x, y) = log(x 2y2) when −5 ≤ x, y ≤
5, with greens color map.
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# Define the function
def f(x, y):
return np.log(x**2 * y**2)
# Create a grid of x and y values
x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
X, Y = np.meshgrid(x, y)
# Create a 3D plot
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# Plot the contours
contours = ax.contour(X, Y, f(X, Y), levels=np.linspace(-10, 10, 20), cmap='Greens')
# Set the axis labels
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
# Set the title
ax.set_title('3D Contours of f(x, y) = log(x^2y^2)')
# Show the plot
plt.show()
(c) Write a Python program to reflect the line segment joining the points A[−5, 2] and B[1, 3]
through the line y = x.
import numpy as np
import matplotlib.pyplot as plt
# Define the points A and B
A = np.array([-5, 2])
B = np.array([1, 3])
# Find the slope and y-intercept of the line AB
m_AB = (B[1] - A[1]) / (B[0] - A[0])
b_AB = A[1] - m_AB * A[0]
# Find the slope and y-intercept of the line y = x
m_yx = 1
b_yx = 0
# Find the point of intersection of the lines AB and y = x
x_intersect = (b_yx - b_AB) / (m_AB - m_yx)
y_intersect = m_yx * x_intersect + b_yx
# Find the reflection of point A through the line y = x
A_reflected = np.array([x_intersect, y_intersect]) - 2 * (m_yx * (A[0] - x_intersect) + (A[1] -
y_intersect)) / (m_yx**2 + 1) * np.array([m_yx, 1])
# Find the reflection of point B through the line y = x
B_reflected = np.array([x_intersect, y_intersect]) - 2 * (m_yx * (B[0] - x_intersect) + (B[1] -
y_intersect)) / (m_yx**2 + 1) * np.array([m_yx, 1])
# Plot the original line segment AB
plt.plot([A[0], B[0]], [A[1], B[1]], 'k-')
# Plot the reflected line segment A'B'
plt.plot([A_reflected[0], B_reflected[0]], [A_reflected[1], B_reflected[1]], 'r-')
# Plot the line y = x
plt.plot([-6, 6], [-6, 6], 'k--')
# Set the axis limits
plt.xlim(-6, 6)
plt.ylim(-6, 6)
# Show the plot
plt.show()
Q.2 Attempt any TWO of the following. [10]
(a) Write a python program to rotate the line segment by 180 degrees having end points (1, 0) and
(2, −1).
import numpy as np
import matplotlib.pyplot as plt
# Define the points A and B
A = np.array([1, 0])
B = np.array([2, -1])
# Find the midpoint of the line segment AB
C = (A + B) / 2
# Rotate the point C by 180 degrees around the origin
D = -C
# Find the reflected points A' and B'
A_reflected = D + (A - C)
B_reflected = D + (B - C)
# Plot the original line segment AB
plt.plot([A[0], B[0]], [A[1], B[1]], 'k-')
# Plot the reflected line segment A'B'
plt.plot([A_reflected[0], B_reflected[0]], [A_reflected[1], B_reflected[1]], 'r-')
# Set the axis limits
plt.xlim(0, 3)
plt.ylim(-2, 1)
# Show the plot
plt.show()
(b) Write a python program to plot triangle with vertices [3, 3], [5, 6], [5, 2], and its rotation about the
origin by angle −π radians.
import numpy as np
import matplotlib.pyplot as plt
# Define the vertices of the triangle
A = np.array([3, 3])
B = np.array([5, 6])
C = np.array([5, 2])
# Plot the triangle
plt.plot([A[0], B[0], C[0], A[0]], [A[1], B[1], C[1], A[1]], 'k-')
# Rotate the triangle by -π radians around the origin
D = np.array([0, 0])
E = np.array([0, 0])
F = np.array([0, 0])
for i in range(3):
v = np.array([A[i], B[i], C[i]])
v_rot = np.dot(np.array([[np.cos(-np.pi), -np.sin(-np.pi)], [np.sin(-np.pi), np.cos(-np.pi)]]), v - D)
+D
if i == 0:
D = v_rot
elif i == 1:
E = v_rot
else:
F = v_rot
# Plot the rotated triangle
plt.plot([D[0], E[0], F[0], D[0]], [D[1], E[1], F[1], D[1]], 'r-')
# Set the axis limits
plt.xlim(0, 6)
plt.ylim(0, 7)
# Show the plot
plt.show()
(c) Write a python program to drawn a polygon with vertices (0, 0), (1, 0), (2, 2), (1, 4) and find its
area and perimeter.
import matplotlib.pyplot as plt
# Define the vertices of the polygon
vertices = [(0, 0), (1, 0), (2, 2), (1, 4)]
# Plot the polygon
x = [v[0] for v in vertices]
y = [v[1] for v in vertices]
plt.plot(x, y, 'k-')
# Find the perimeter of the polygon
perimeter = sum([((vertices[i+1][0] - vertices[i][0])**2 + (vertices[i+1][1] - vertices[i][1])**2)**0.5
for i in range(len(vertices)-1)])
# Find the area of the polygon
area = 0.5 * abs(sum([vertices[i][0]*vertices[i+1][1] - vertices[i+1][0]*vertices[i][1] for i in
range(len(vertices)-1)]))
# Print the results
print("Perimeter:", perimeter)
print("Area:", area)
# Show the plot
plt.show()
Q.3 Attempt the following.
(a) Attempt any ONE of the following. [7]
i. Write a Python program to solve the following LPP:
Max Z = 4x + y + 3z + 5w
subject to 4x + 6y − 5z − 4w ≥ −20
−8x − 3y + 3z + 2w ≤ 20
x ≥ 0, y ≥ 0.
import numpy as np
from scipy.optimize import linprog
# Define the objective function
c = np.array([4, 1, 3, 5])
# Define the constraints
A_ub = np.array([[4, 6, -5, -4], [-8, -3, 3, 2]])
b_ub = np.array([-20, 20])
# Define the bounds
bounds = [(0, None), (0, None), (0, None), (0, None)]
# Solve the LPP
res = linprog(c=c, A_ub=A_ub, b_ub=b_ub, bounds=bounds)
# Print the results
print("Optimal solution found:")
print("x =", res.x[0])
print("y =", res.x[1])
print("z =", res.x[2])
print("w =", res.x[3])
print("Maximum value of Z =", res.fun)
ii. Write a Python program to solve the following LPP:
Max Z = x + y
subject to x ≤ 6
y≤6
x + y ≤ 11
x ≥ 0, y ≥ 0.
import numpy as np
from scipy.optimize import linprog
# Define the objective function
c = np.array([1, 1])
# Define the constraints
A_ub = np.array([[1, 1], [0, 1], [1, 0]])
b_ub = np.array([6, 6, 11])
# Define the bounds
bounds = [(0, 6), (0, 6)]
# Solve the LPP
res = linprog(c=c, A_ub=A_ub, b_ub=b_ub, bounds=bounds)
# Print the results
print("Optimal solution found:")
print("x =", res.x[0])
print("y =", res.x[1])
print("Maximum value of Z =", res.fun)
32
(b) Attempt any ONE of the following. [8]
i. Apply each of the following transformations on the point P [3, −1].
I. Reflection through X-axis.
II. Scaling in Y-coordinate by factor 1.5.
III. Shearing in both X and Y direction by -2 and 4 units respectively.
IV. Rotation about origin by an angle 30 degrees.
import math
def reflection_x_axis(point):
return [point[0], -point[1]]
def scaling_y(point, factor):
return [point[0], point[1] * factor]
def shearing_xy(point, x_shift, y_shift):
return [point[0] + x_shift * point[1], point[1] + y_shift * point[0]]
def rotation_origin(point, angle_in_degrees):
angle_in_radians = math.radians(angle_in_degrees)
sin_angle = math.sin(angle_in_radians)
cos_angle = math.cos(angle_in_radians)
return [point[0] * cos_angle - point[1] * sin_angle, point[0] * sin_angle + point[1] *
cos_angle]
point_P = [3, -1]
transformations = [
reflection_x_axis,
lambda point: scaling_y(point, 1.5),
lambda point: shearing_xy(point, -2, 4),
lambda point: rotation_origin(point, 30)
]
for transformation in transformations:
point_P = transformation(point_P)
print(f"After {type(transformation).__name__}: {point_P}")
ii. Write a python program to draw polygon with vertices [3, 3], [4, 6], [5, 4], [4, 2] and [2, 2],
and its translation in x and y direction by factors -2 and 1 respectively.
import turtle
# Define the vertices of the polygon
vertices = [(3, 3), (4, 6), (5, 4), (4, 2), (2, 2)]
# Create a turtle object
t = turtle.Turtle()
t.speed(0)
# Draw the polygon
t.penup()
t.goto(vertices[0][0], vertices[0][1])
t.pendown()
for vertex in vertices:
t.goto(vertex[0], vertex[1])
# Translate the polygon in the x and y directions
t.penup()
t.goto(-2, 1)
t.pendown()
for vertex in vertices:
t.goto(vertex[0] - 2, vertex[1] + 1)
# Keep the window open
turtle.done()
33
SAVITRIBAI PHULE PUNE UNIVERSITY, PUNE Board of Studies in Mathematics S.Y.B.Sc (Computer
Science) Practical Examination in Mathematics MTC-243: Python Programming Language-II (CBCS 2019
Pattern)(Semester-IV)
Slip No. : 18
Time: 3 Hours Max. Marks: 35
Q.1 Attempt any TWO of the following. [10]
(a) Write a python program to draw polygon with vertices [3, 3], [4, 6], [2, 5], [2, 2], and its
translation in x and y directions using the factors 3, 5 respectively.
import matplotlib.pyplot as plt
# Define the vertices of the polygon
vertices = [(3, 3), (4, 6), (2, 5), (2, 2)]
# Create a figure and a set of axes
fig, ax = plt.subplots()
# Plot the original polygon
polygon = plt.Polygon(vertices, color='blue')
ax.add_patch(polygon)
# Translate the polygon in the x and y directions
translated_vertices = [(x + 3, y + 5) for x, y in vertices]
translated_polygon = plt.Polygon(translated_vertices, color='red')
ax.add_patch(translated_polygon)
# Set the limits of the axes
ax.set_xlim([-10, 20])
ax.set_ylim([-10, 20])
# Show the plot
plt.show()
(b) Write a Python program to plot the graph 2x2 − 4x + 5 in [–10, 10] in magenta colored dashed
pattern.
import matplotlib.pyplot as plt
import numpy as np
# Define the function
def f(x):
return 2*x**2 - 4*x + 5
# Generate x values from -10 to 10 with 0.1 spacing
x = np.arange(-10, 10, 0.1)
# Generate y values from the function
y = f(x)
# Create a figure and a set of axes
fig, ax = plt.subplots()
# Plot the function with a magenta colored dashed pattern
ax.plot(x, y, color='magenta', linestyle='--')
# Set the limits of the axes
ax.set_xlim([-10, 10])
ax.set_ylim([-5, 35])
# Show the plot
plt.show()
(c) Write a Python program to generate 3D plot of the functions z = x2 + y2 in −5 < x, y < 5.
import matplotlib.pyplot as plt
import numpy as np
# Define the x and y ranges
x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
# Create a meshgrid of x and y values
X, Y = np.meshgrid(x, y)
# Define the z function
Z = X**2 + Y**2
# Create a 3D plot
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# Plot the surface
ax.plot_surface(X, Y, Z, cmap='viridis')
# Set the limits of the axes
ax.set_xlim([-5, 5])
ax.set_ylim([-5, 5])
ax.set_zlim([0, 50])
# Show the plot
plt.show()
Q.2 Attempt any TWO of the following. [10]
(a) Write a Python program to generate vector x in the interval [−22, 22] using numpy package with
80 subintervals.
import numpy as np
# Generate a vector of 80 points between -22 and 22
x = np.linspace(-22, 22, 80)
# Print the vector x
print(x)
(b) Write a Python program to rotate the triangle ABC by 90 degree, where A[1, 2], B[2, −2]andC[−1, 2].
import numpy as np
import matplotlib.pyplot as plt
# Define the vertices of the triangle
A = np.array([1, 2])
B = np.array([2, -2])
C = np.array([-1, 2])
# Define the rotation matrix
rotation_matrix = np.array([[0, -1], [1, 0]])
# Rotate the vertices of the triangle
A_rotated = np.dot(rotation_matrix, A)
B_rotated = np.dot(rotation_matrix, B)
C_rotated = np.dot(rotation_matrix, C)
# Plot the original triangle
plt.plot(A[0], A[1], 'o')
plt.plot(B[0], B[1], 'o')
plt.plot(C[0], C[1], 'o')
plt.plot([A[0], B[0], C[0], A[0]], [A[1], B[1], C[1], A[1]], 'k-')
# Plot the rotated triangle
plt.plot(A_rotated[0], A_rotated[1], 'o')
plt.plot(B_rotated[0], B_rotated[1], 'o')
plt.plot(C_rotated[0], C_rotated[1], 'o')
plt.plot([A_rotated[0], B_rotated[0], C_rotated[0], A_rotated[0]], [A_rotated[1], B_rotated[1],
C_rotated[1], A_rotated[1]], 'r--')
# Add labels and title
plt.xlabel('x')
plt.ylabel('y')
plt.title('Rotated Triangle')
# Show the plot
plt.show()
(c) Write a Python program to plot the rectangle with vertices at [2, 1], [2, 4], [5, 4], [5, 1], and its
uniform expansion by factor 4.
import matplotlib.pyplot as plt
# Define the vertices of the rectangle
vertices = [(2, 1), (2, 4), (5, 4), (5, 1)]
# Define the expanded vertices of the rectangle
expanded_vertices = [(2*x, 2*y) for x, y in vertices]
# Plot the original rectangle
plt.plot(*zip(*vertices), color='blue')
# Plot the expanded rectangle
plt.plot(*zip(*expanded_vertices), color='red', linestyle='--')
# Add labels and title
plt.xlabel('x')
plt.ylabel('y')
plt.title('Rectangle and its uniform expansion')
# Show the plot
plt.show()
Q.3 Attempt the following.
(a) Attempt any ONE of the following. [7]
i. Write a Python program to solve the following LPP:
Min Z = x + y
subject to x ≥ 6
y≥6
x + y ≤ 11
x ≥ 0, y ≥ 0.
import numpy as np
from scipy.optimize import linprog
# Define the objective function
c = np.array([1, 1])
# Define the constraints
A_ub = np.array([[0, 1], [1, 1], [-1, -1]])
b_ub = np.array([11, 6, 6])
A_eq = None
b_eq = None
# Define the bounds
bounds = [(6, None), (6, None)]
# Solve the LPP
res = linprog(c, A_ub=A_ub, b_ub=b_ub, A_eq=A_eq, b_eq=b_eq, bounds=bounds)
# Print the solution
print("Optimal solution found:")
print("x =", res.x[0])
print("y =", res.x[1])
print("Minimum value of Z =", res.fun)
ii. Write a Python program to solve the following LPP:
Max Z = 2x + 3y
subject to 5x − y ≥ 0
x+y≥6
x ≥ 0, y ≥ 0.
import numpy as np
from scipy.optimize import linprog
# Define the objective function
c = np.array([2, 3])
# Define the constraints
A_ub = np.array([[5, -1], [1, 1], [-1, 0]])
b_ub = np.array([0, 6, 0])
A_eq = None
b_eq = None
# Define the bounds
bounds = [(0, None), (0, None)]
# Solve the LPP
res = linprog(c, A_ub=A_ub, b_ub=b_ub, A_eq=A_eq, b_eq=b_eq, bounds=bounds, method='simplex')
# Print the solution
print("Optimal solution found:")
print("x =", res.x[0])
print("y =", res.x[1])
print("Maximum value of Z =", res.fun)
34
(b) Attempt any ONE of the following. [8]
i. Write a Python program to find the combined transformation of the line segment between
the points A[3, 2] and B[2, −3] for the following sequence of transformations:
I. First rotation about origin through an angle π/6
II. Followed by scaling in Y coordinates by 4 units respectively.
III. Followed by reflection through the origin.
import numpy as np
# Define the points A and B
A = np.array([3, 2])
B = np.array([2, -3])
# Define the transformation matrices
R = np.array([[np.cos(np.pi/6), -np.sin(np.pi/6)],
[np.sin(np.pi/6), np.cos(np.pi/6)]])
S = np.array([[1, 0],
[0, 4]])
F = np.array([[-1, 0],
[0, -1]])
# Apply the transformations
T1 = R @ A
T2 = R @ B
T3 = S @ T1
T4 = S @ T2
T5 = F @ T3
T6 = F @ T4
# Print the transformed points
print("Transformed points A and B:")
print("A =", T5)
print("B =", T6)
ii. Apply each of the following transformations on the point P [3, −1].
I. Reflection through Y-axis.
II. Scaling in X and Y direction by 1/2 and 3 units respectively.
III. Shearing in both X and Y direction by -2 and 4 units respectively.
IV. Rotation about origin by an angle 60 degrees.
import numpy as np
# Define the point P
P = np.array([3, -1])
# Define the transformation matrices
Fy = np.array([[-1, 0],
[0, 1]])
Sx = np.array([[1/2, 0],
[0, 1]])
Sy = np.array([[1, 0],
[0, 3]])
Shx = np.array([[1, -2],
[0, 1]])
Shy = np.array([[1, 0],
[4, 1]])
R = np.array([[np.cos(np.pi/3), -np.sin(np.pi/3)],
[np.sin(np.pi/3), np.cos(np.pi/3)]])
# Apply the transformations
T1 = Fy @ P
T2 = Sx @ T1
T3 = Sy @ T2
T4 = Shx @ T3
T5 = Shy @ T4
T6 = R @ T5
# Print the transformed points
print("Transformed point P:")
print("P =", T6)
35
SAVITRIBAI PHULE PUNE UNIVERSITY, PUNE Board of Studies in Mathematics S.Y.B.Sc (Computer
Science) Practical Examination in Mathematics MTC-243: Python Programming Language-II (CBCS 2019
Pattern)(Semester-IV)
Slip No. : 19
Time: 3 Hours Max. Marks: 35
Q.1 Attempt any TWO of the following. [10]
(a) Write a python program to plot the graphs of sin(x), ex and x3 in [0, 5] in one figure with 2 × 2
subplots.
import numpy as np
import matplotlib.pyplot as plt
fig, axs = plt.subplots(2, 2, figsize=(10, 10))
x = np.linspace(0, 5, 100)
axs[0, 0].plot(x, np.sin(x))
axs[0, 0].set_title('sin(x)')
axs[0, 1].plot(x, np.exp(x))
axs[0, 1].set_title('e^x')
axs[1, 0].plot(x, x**3)
axs[1, 0].set_title('x^3')
axs[1, 1].plot(x, x**3, label='x^3')
axs[1, 1].plot(x, np.exp(x), label='e^x')
axs[1, 1].plot(x, np.sin(x), label='sin(x)')
axs[1, 1].set_title('x^3, e^x, sin(x)')
axs[1, 1].legend()
plt.show()
(b) Write a python program to plot 3D Surface Plot of the function z = cos(|x|+ |y|) in −1 < x, y < 1.
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
x = np.linspace(-1, 1, 20)
y = np.linspace(-1, 1, 20)
X, Y = np.meshgrid(x, y)
Z = np.cos(np.abs(X) + np.abs(Y))
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(X, Y, Z, cmap='viridis')
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
ax.set_title('3D Surface Plot of z = cos(|x|+ |y|) in -1 < x, y < 1')
plt.show()
(c) Write a python program to plot 2D graph of the functions f(x) = log(x) + 5 and g(x) = log(x) − 5 in
[0, 10] by setting different line width and different colors to the curve.
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0.01, 10, 100) # x values from 0.01 to 10 with 100 points
# plot f(x) = log(x) + 5 in blue with a line width of 2
plt.plot(x, np.log(x) + 5, color='blue', linewidth=2)
# plot g(x) = log(x) - 5 in green with a line width of 3
plt.plot(x, np.log(x) - 5, color='green', linewidth=3)
# set the x and y axis labels
plt.xlabel('x')
plt.ylabel('f(x) and g(x)')
# set the title of the plot
plt.title('Graphs of f(x) = log(x) + 5 and g(x) = log(x) - 5')
# display the plot
plt.show()
Q.2 Attempt any TWO of the following. [10]
(a) Write a python program to rotate the ray by 90o in clockwise direction having starting point (0, 0)
and end point (4, 4).
import matplotlib.pyplot as plt
# starting point
x1, y1 = 0, 0
# end point
x2, y2 = 4, 4
# rotate the ray by 90 degrees in clockwise direction
x3 = y1
y3 = -x1
x4 = y2
y4 = -x2
# plot the original ray
plt.plot([x1, x2], [y1, y2], color='blue', linewidth=2)
# plot the rotated ray
plt.plot([x3, x4], [y3, y4], color='red', linewidth=2)
# add labels and title
plt.xlabel('X', fontsize=12)
plt.ylabel('Y', fontsize=12)
plt.title('Ray rotation by 90 degrees in clockwise direction', fontsize=14)
# show the plot
plt.show()
(b) Write a Python program to Reflect the triangle ABC through the line y=3, where A[1, 0], B[2, −1]
and C[−1, 3]
import matplotlib.pyplot as plt
# define the vertices of the original triangle
A = (1, 0)
B = (2, -1)
C = (-1, 3)
# define the reflection line
line = (0, 3)
# calculate the slope of the reflection line
m=0
# calculate the reflected points
A_reflected = (A[0], 2*line[1] - A[1])
B_reflected = (B[0], 2*line[1] - B[1])
C_reflected = (C[0], 2*line[1] - C[1])
# plot the original triangle
plt.plot([A[0], B[0], C[0], A[0]], [A[1], B[1], C[1], A[1]], color='blue', linewidth=2)
# plot the reflected triangle
plt.plot([A_reflected[0], B_reflected[0], C_reflected[0], A_reflected[0]], [A_reflected[1],
B_reflected[1], C_reflected[1], A_reflected[1]], color='red', linewidth=2)
# plot the reflection line
plt.plot([-10, 10], [line[1], line[1]], color='green', linewidth=1)
# add labels and title
plt.xlabel('X', fontsize=12)
plt.ylabel('Y', fontsize=12)
plt.title('Reflection of Triangle ABC through the line y=3', fontsize=14)
# show the plot
plt.show()
(c) Write a Python program to draw a polygon with vertices (0, 0), (1, 0), (2, 2), (1, 4). Also find area
and perimeter of the polygon.
import matplotlib.pyplot as plt
# define the vertices of the polygon
vertices = [(0, 0), (1, 0), (2, 2), (1, 4)]
# calculate the perimeter of the polygon
perimeter = sum([((vertices[i][0] - vertices[i-1][0])**2 + (vertices[i][1] - vertices[i-1][1])**2)**0.5 for
i in range(1, len(vertices))]) + ((vertices[0][0] - vertices[-1][0])**2 + (vertices[0][1] - vertices[-
1][1])**2)**0.5
# calculate the area of the polygon using the shoelace formula
area = 0.5 * sum([vertices[i][0] * (vertices[i+1][1] - vertices[i-1][1]) for i in range(len(vertices))])
# plot the polygon
plt.plot([vertex[0] for vertex in vertices], [vertex[1] for vertex in vertices], color='blue', linewidth=2)
# add labels and title
plt.xlabel('X', fontsize=12)
plt.ylabel('Y', fontsize=12)
plt.title('Polygon with Vertices (0, 0), (1, 0), (2, 2), (1, 4)', fontsize=14)
# display the calculated area and perimeter
print(f'Area: {area:.2f}')
print(f'Perimeter: {perimeter:.2f}')
# show the plot
plt.show()
Q.3 Attempt the following.
(a) Attempt any ONE of the following. [7]
i. Write a Python program to solve the following LPP:
Max Z = 3x + 5y + 4z
subject to 2x + 3y ≤ 8
2y + 5z ≤ 10
3x + 2y + 4z ≤ 15
x ≥ 0, y ≥ 0.
import pulp
# Create a new LP problem
prob = pulp.LpProblem("Maximize Z", pulp.LpMaximize)
# Define the variables
x = pulp.LpVariable("x", lowBound=0)
y = pulp.LpVariable("y", lowBound=0)
z = pulp.LpVariable("z")
# Define the objective function
prob += 3 * x + 5 * y + 4 * z
# Define the constraints
prob += 2 * x + 3 * y <= 8
prob += 2 * y + 5 * z <= 10
prob += 3 * x + 2 * y + 4 * z <= 15
# Solve the problem
prob.solve()
# Print the results
print("Optimal value of Z:", prob.objective.value())
print("Optimal value of x:", x.varValue)
print("Optimal value of y:", y.varValue)
print("Optimal value of z:", z.varValue)
ii. Write a Python program to solve the following LPP:
Min Z = x + 2y + z
1 1
subject to x +
3
2y+ 2z≤1
2 x + 2y + z ≥ 8
x ≥ 0, y ≥ 0.
import pulp
# Create a new LP problem
prob = pulp.LpProblem("Minimize Z", pulp.LpMinimize)
# Define the variables
x = pulp.LpVariable("x", lowBound=0)
y = pulp.LpVariable("y", lowBound=0)
z = pulp.LpVariable("z", lowBound=0)
# Define the objective function
prob += x + 2 * y + z
# Define the constraints
prob += x + 2 * y + 2 * z <= 1
prob += 2 * x + 2 * y + z >= 8
# Solve the problem
prob.solve()
# Print the results
print("Optimal value of Z:", prob.objective.value())
print("Optimal value of x:", x.varValue)
print("Optimal value of y:", y.varValue)
print("Optimal value of z:", z.varValue)
36
(b) Attempt any ONE of the following. [8]
i. Write the Python program to apply each of the following transformation on the point P = [−2,
4].
I. Rotation about origin through an angle 48
degree II. Scaling in X-coordinate by factor 2
III. Reflection through the line y = 2x − 3
IV. Shearing in X direction by 7 units
import numpy as np
# Define the point P
P = np.array([-2, 4])
# I. Rotation about origin through an
angle 48 degree
theta = np.deg2rad(48)
rotation_matrix = np.array([[np.cos(theta),
-np.sin(theta)],
[np.sin(theta),
np.cos(theta)]])
P_rotated = np.dot(rotation_matrix, P)
# II. Scaling in X-coordinate by factor 2
scaling_matrix = np.array([[2, 0],
[0, 1]])
P_scaled = np.dot(scaling_matrix,
P_rotated)
# III. Reflection through the line y = 2x - 3
reflection_matrix = np.array([[0, 1],
[1, -2]])
P_reflected = np.dot(reflection_matrix,
P_scaled) + np.array([0, -3])
# IV. Shearing in X direction by 7 units
shearing_matrix = np.array([[1, 7],
[0, 1]])
P_sheared = np.dot(shearing_matrix,
P_reflected)
# Print the transformed point
print("Transformed point:", P_sheared)
ii. Find combined transformation of the line segment between the points A[4, −1] and B[3, 0]
for the following sequence of transformations:
First rotation about origin through an angle πc; followed by scaling in x coordinate by 3
units; followed by reflection through the line y = x.
import numpy as np
# Define the points A and B
A = np.array([4, -1])
B = np.array([3, 0])
# Rotation about origin through an angle π (180 degrees)
def rotate(point):
return np.array([-point[0], -point[1]])
A_rotated = rotate(A)
B_rotated = rotate(B)
# Scaling in x coordinate by 3 units
def scale_x(point):
return np.array([3 * point[0], point[1]])
A_scaled = scale_x(A_rotated)
B_scaled = scale_x(B_rotated)
# Reflection through the line y = x
def reflect(point):
return np.array([point[1], point[0]])
A_reflected = reflect(A_scaled)
B_reflected = reflect(B_scaled)
print("Combined transformation of point A:", A_reflected)
print("Combined transformation of point B:", B_reflected)
37
SAVITRIBAI PHULE PUNE UNIVERSITY, PUNE Board of Studies in Mathematics S.Y.B.Sc (Computer
Science) Practical Examination in Mathematics MTC-243: Python Programming Language-II (CBCS 2019
Pattern)(Semester-IV)
Slip No. : 20
Time: 3 Hours Max. Marks: 35
Q.1 Attempt any TWO of the following. [10]
(a) Write a Python program to plot 2D graph of the function f(x) = sin x and g(x) = cos x in [−2π, 2π].
import numpy as np
import matplotlib.pyplot as plt
# Define the x-axis range
x = np.linspace(-2*np.pi, 2*np.pi, 400)
# Calculate the y-values for f(x) = sin x and g(x) = cos x
f_x = np.sin(x)
g_x = np.cos(x)
# Create the plot
plt.plot(x, f_x, label='f(x) = sin x')
plt.plot(x, g_x, label='g(x) = cos x')
# Add title and labels
plt.title('2D Graph of f(x) = sin x and g(x) = cos x')
plt.xlabel('x')
plt.ylabel('y')
# Add legend
plt.legend()
# Show the plot
plt.show()
(b) Write a Python program to plot the 2D graph of the function f(x) = ex sin x in [−5π, 5π] with blue
points line with upward pointing triangle.
import numpy as np
import matplotlib.pyplot as plt
# Define the x-axis range
x = np.linspace(-5*np.pi, 5*np.pi, 400)
# Calculate the y-values for f(x) = e^(sin x)
f_x = np.exp(np.sin(x))
# Create the plot
plt.plot(x, f_x, 'b^', markersize=5, label='f(x) = e^(sin x)')
# Add title and labels
plt.title('2D Graph of f(x) = e^(sin x)')
plt.xlabel('x')
plt.ylabel('y')
# Add legend
plt.legend()
# Show the plot
plt.show()
(c) Write a Python program to plot the 3D graph of the function f(x) = sin(x 2 + y2), −6 < x, y < 6.
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# Define the range of x and y
x = np.linspace(-6, 6, 100)
y = np.linspace(-6, 6, 100)
# Create a meshgrid of x and y
X, Y = np.meshgrid(x, y)
# Calculate the z-values for the function f(x, y) = sin(x^2 + y^2)
Z = np.sin(X**2 + Y**2)
# Create a 3D plot
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# Plot the surface
ax.plot_surface(X, Y, Z, cmap='viridis')
# Set the limits of the x, y, and z axes
ax.set_xlim(-6, 6)
ax.set_ylim(-6, 6)
ax.set_zlim(-1, 1)
# Set the labels of the x, y, and z axes
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')
# Set the title of the plot
ax.set_title('3D graph of f(x, y) = sin(x^2 + y^2)')
# Show the plot
plt.show()
Q.2 Attempt any TWO of the following. [10]
(a) Write a python program to reflect the line segment joining the points A[−5, 2], B[3, −4] through
the line y = 2x − 1.
import numpy as np
# Define the points A and B
A = np.array([-5, 2])
B = np.array([3, -4])
# Define the slope and y-intercept of the line y = 2x - 1
m=2
b = -1
# Calculate the slope of the line perpendicular to y = 2x - 1
m_perp = -1/m
# Calculate the point C where the line segment AB intersects the line y = 2x - 1
C = (A[1] - m*A[0] + m*b) / (m**2 + 1) * np.array([1, m]) + b * np.array([0, -1])
# Calculate the reflection of A and B through the line y = 2x - 1
A_refl = 2*C - A
B_refl = 2*C - B
# Print the coordinates of the original and reflected points
print("Original points: A =", A, "B =", B)
print("Reflected points: A' =", A_refl, "B' =", B_refl)
(b) Write a Python program to find the area and perimeter of a polygon with vertices (0, 0), (−2, 0), (5, 5), (1, −6).
import math
# Define the vertices of the polygon
vertices = [(0, 0), (-2, 0), (5, 5), (1, -6)]
# Calculate the number of sides of the polygon
n = len(vertices)
# Calculate the area of the polygon using the shoelace formula
area = 0
for i in range(n):
j = (i + 1) % n
area += (vertices[i][0] * vertices[j][1]) - (vertices[j][0] * vertices[i][1])
area = abs(area / 2)
# Calculate the perimeter of the polygon
perimeter = 0
for i in range(n):
j = (i + 1) % n
perimeter += math.sqrt((vertices[j][0] - vertices[i][0])**2 + (vertices[j][1] - vertices[i][1])**2)
# Print the area and perimeter of the polygon
print("Area of the polygon:", area)
print("Perimeter of the polygon:", perimeter)
(c) Write a Python program to plot the 3D graph of the function f(x, y) = sin x+cos y, x, y ∈ [−2π, 2π]
using wireframe plot.
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# Define the x and y ranges
x = np.linspace(-2*np.pi, 2*np.pi, 100)
y = np.linspace(-2*np.pi, 2*np.pi, 100)
# Create a meshgrid of x and y values
X, Y = np.meshgrid(x, y)
# Calculate the z values for each (x, y) pair
Z = np.sin(X) + np.cos(Y)
# Create a 3D plot
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# Plot the wireframe of the function
ax.plot_wireframe(X, Y, Z, color='black')
# Set the axis labels and limits
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')
ax.set_xlim([-2*np.pi, 2*np.pi])
ax.set_ylim([-2*np.pi, 2*np.pi])
ax.set_zlim([-2, 2])
# Show the plot
plt.show()
Q.3 Attempt the following.
(a) Attempt any ONE of the following. [7]
i. Write a Python program to solve the following LPP:
Max Z = x + y
subject to x − y ≥ 1
x+y≥2
x ≥ 0, y ≥ 0.
import numpy as np
from scipy.optimize import linprog
# Define the objective function and constraints
c = np.array([1, 1])
A_ub = np.array([[1, -1], [1, 1], [1, 0], [0, 1]])
b_ub = np.array([1, 2, 0, 0])
# Set the bounds for x and y
bounds = [(0, None), (0, None)]
# Solve the LPP using linprog
res = linprog(c, A_ub=A_ub, b_ub=b_ub, bounds=bounds)
# Print the solution
print("Optimal solution found:")
print("x =", res.x[0])
print("y =", res.x[1])
print("Maximum value of Z =", res.fun)
ii. Write a Python program to solve the following LPP:
Min Z = 3.5x + 2y
subject to x − y ≥ 5
x≥4
y≤2
x ≥ 0, y ≥ 0.
import pulp
# Create a LpProblem object
prob = pulp.LpProblem("Minimize_Z", pulp.LpMinimize)
# Create decision variables
x = pulp.LpVariable("x", lowBound=0)
y = pulp.LpVariable("y", lowBound=0)
# Define the objective function
prob += 3.5 * x + 2 * y
# Add constraints
prob += x - y >= 5
prob += x >= 4
prob += y <= 2
# Solve the problem
prob.solve()
# Print the results
print("Status:", pulp.LpStatus[prob.status])
print("Objective value:", prob.objective())
print("Decision variables:")
print("x =", x.varValue)
print("y =", y.varValue)
38
(b) Attempt any ONE of the following. [8]
i. Apply the following transformations on the point P [3, −2]
I. Scaling in y direction by 4 units.
II. Reflection through y axis.
III. Rotation about origin by an angle 45o.
IV. Reflection through the line y = x.
import math
def scale_y(x, y, sy):
return x, sy * y
def reflect_y(x, y):
return -x, y
def rotate_origin(x, y, angle):
angle_rad = math.radians(angle)
return x * math.cos(angle_rad) - y * math.sin(angle_rad), x * math.sin(angle_rad) + y *
math.cos(angle_rad)
def reflect_y_x(x, y):
return y, x
p = [3, -2]
p = scale_y(p[0], p[1], 4)
p = reflect_y(p[0], p[1])
p = rotate_origin(p[0], p[1], 45)
p = reflect_y_x(p[0], p[1])
print(p) # Output: [(-11/√2), (5/√2)]
ii. Apply the following transformations on the point P [3, −2]
I. Shearing in x direction by -2 units.
II. Scaling in x and y direction by -3 and 2 units respectively.
III. Reflection through x axis.
IV. Reflection through the line y = −x.
def shear_x(x, y, sh_x):
return x + sh_x * y, y
def scale(x, y, sx, sy):
return sx * x, sy * y
def reflect_x(x, y):
return x, -y
def reflect_y_x(x, y):
return y, x
p = [3, -2]
p = shear_x(p[0], p[1], -2)
p = scale(p[0], p[1], -3, 2)
p = reflect_x(p[0], p[1])
p = reflect_y_x(p[0], p[1])
print(p) # Output: [-4, 21]
39
SAVITRIBAI PHULE PUNE UNIVERSITY, PUNE Board of Studies in Mathematics S.Y.B.Sc (Computer
Science) Practical Examination in Mathematics MTC-243: Python Programming Language-II (CBCS 2019
Pattern)(Semester-IV)
Slip No. : 21
Time: 3 Hours Max. Marks: 35
Q.1 Attempt any TWO of the following. [10]
(a) Write a Python program to plot 2D graph of the function f(x) = x 4 in [0, 5] with red dashed line
with circle markers.
import numpy as np
import matplotlib.pyplot as plt
# Define the x range
x = np.linspace(0, 5, 100)
# Calculate the y values
y = x ** 4
# Create the plot
plt.plot(x, y, linestyle='--', color='red', marker='o', markersize=3, label='f(x) = x^4')
# Set the plot title, x and y labels
plt.title('2D Graph of f(x) = x^4 in [0, 5]')
plt.xlabel('x')
plt.ylabel('y')
# Enable grid
plt.grid(True)
# Enable legend
plt.legend()
# Show the plot
plt.show()
(b) Write a Python program to generate 3D plot of the function z = x 2 + y2 in −6 < x, y < 6.
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# Define the x and y ranges
x = np.linspace(-6, 6, 40)
y = np.linspace(-6, 6, 40)
# Create a meshgrid for the x and y values
X, Y = np.meshgrid(x, y)
# Calculate the z values
Z = X**2 + Y**2
# Create the 3D plot
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(X, Y, Z, cmap='viridis', edgecolor='none')
# Set the plot title, x, y, and z labels
ax.set_title('3D Plot of z = x^2 + y^2 in -6 < x, y < 6')
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')
# Show the plot
plt.show()
(c) Write a Python program to plot the 3D graph of the function f(x) = ex2+y2 for x, y ∈ [0, 2π] using
wireframe.
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# Define the x and y ranges
x = np.linspace(0, 2 * np.pi, 20)
y = np.linspace(0, 2 * np.pi, 20)
# Create a meshgrid for the x and y values
X, Y = np.meshgrid(x, y)
# Calculate the z values
Z = np.exp(X**2 + Y**2)
# Create the 3D plot with wireframe
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_wireframe(X, Y, Z, color='black')
# Set the plot title, x, y, and z labels
ax.set_title('3D Plot of f(x, y) = e^(x^2 + y^2) for x, y ∈ [0, 2π] using wireframe')
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')
# Show the plot
plt.show()
Q.2 Attempt any TWO of the following. [10]
(a) If the line segment joining the points A[2, 5] and B[4, − 13] is transformed to the line segment A B
′ ′
2 3
by the transformation matrix [T ] = 4 1 , then using python find the slope and midpoint of the
transformed line.
# coordinates of points A and B
A = [2, 5]
B = [4, 13]
# transformation matrix
T = [[2, 3], [4, 1]]
# transformed coordinates of points A and B
A_prime = [sum(a*b for a, b in zip(T[i], A)) for i in range(len(T))]
B_prime = [sum(a*b for a, b in zip(T[i], B)) for i in range(len(T))]
# slope of the transformed line segment A'B'
slope = (B_prime[1] - A_prime[1]) / (B_prime[0] - A_prime[0])
# midpoint of the transformed line segment A'B'
midpoint = [(A_prime[i] + B_prime[i]) / 2 for i in range(len(A_prime))]
print("Slope of the transformed line segment A'B':", slope)
print("Midpoint of the transformed line segment A'B':", midpoint)
(b) Write a python program to plot square with vertices at [4, 4], [2, 4], [2, 2], [4, 2] and find its
uniform expansion by factor 3, uniform reduction by factor 0.4.
import matplotlib.pyplot as plt
import numpy as np
# define the vertices of the square
vertices = np.array([[4, 4], [2, 4], [2, 2], [4, 2]])
# plot the square
plt.plot(vertices[:, 0], vertices[:, 1], 'b-')
plt.xlabel('x')
plt.ylabel('y')
plt.title('Square with Vertices at (4, 4), (2, 4), (2, 2), and (4, 2)')
plt.grid()
plt.show()
# uniform expansion by a factor of 3
expanded_vertices = vertices * 3
# plot the expanded square
plt.plot(expanded_vertices[:, 0], expanded_vertices[:, 1], 'r-')
plt.xlabel('x')
plt.ylabel('y')
plt.title('Expanded Square with Vertices at (12, 12), (6, 12), (6, 6), and (12, 6)')
plt.grid()
plt.show()
# uniform reduction by a factor of 0.4
reduced_vertices = vertices * 0.4
# plot the reduced square
plt.plot(reduced_vertices[:, 0], reduced_vertices[:, 1], 'g-')
plt.xlabel('x')
plt.ylabel('y')
plt.title('Reduced Square with Vertices at (1.6, 1.6), (0.8, 1.6), (0.8, 0.8), and (1.6, 0.8)')
plt.grid()
plt.show()
(c) Write a Python program to find the equation of the transformed line if shearing is applied on the
line 2x + y = 3 in x and y direction by 2 and -3 units respectively.
# original equation of the line
a=2
b=1
c = -3
# shearing factors
m_x = 2
m_y = -3
# transformed equation of the line
a_prime = a
b_prime = b + m_y * a
c_prime = m_x * c + m_y * b + c
# solve for y' in terms of x'
if a_prime != 0:
m_prime = -b_prime / a_prime
c_prime = c_prime - m_prime * (-b_prime)
# print the transformed equation of the line
print("Transformed equation of the line: y' = {:.2f}x' + {:.2f}".format(m_prime, c_prime))
Q.3 Attempt the following.
(a) Attempt any ONE of the following. [7]
i. Write a Python program to solve the following LPP:
Min Z = 4x + 2y
subject to x + y ≤ 3
x−y≥2
x ≥ 0, y ≥ 0.
import numpy as np
# objective function coefficients
c = np.array([4, 2])
# constraint coefficients
A = np.array([[1, 1], [1, -1], [1, 0], [0, 1]])
b = np.array([3, 2, 0, 0])
# number of variables and constraints
n_vars = c.shape[0]
n_constraints = b.shape[0]
# initialize the simplex tableau
Tableau = np.zeros((n_constraints + 1, n_vars + n_constraints))
for i in range(n_constraints):
for j in range(n_vars):
Tableau[i, j] = A[i, j]
Tableau[i, n_vars + i] = b[i]
Tableau[n_constraints, :n_vars] = c
# initialize the artificial variables and their coefficients
Artificial_variables = np.zeros(n_constraints)
Artificial_variables[-1] = 1
Artificial_coefficients = np.append(np.zeros(n_vars), Artificial_variables)
Tableau[:-1, -1] = Artificial_coefficients
# apply the simplex method
while np.any(Tableau[-1, :n_vars] < 0):
# find the entering variable
entering_var_index = np.argmin(Tableau[-1, :n_vars])
entering_var = entering_var_index + 1
# find the leaving variable
leaving_var_index = np.where(Tableau[:, entering_var_index] > 0)[0][0]
leaving_var = leaving_var_index + 1
# pivot on the entering variable
pivot_element = Tableau[leaving_var_index, entering_var_index]
for j in range(n_vars + n_constraints):
Tableau[leaving_var_index, j] /= pivot_element
for i in range(n_constraints + 1):
if i != leaving_var_index:
factor = Tableau[i, entering_var_index]
for j in range(n_vars + n_constraints):
Tableau[i, j] -= factor * Tableau[leaving_var_index, j]
# find the optimal solution
optimal_solution = np.max(Tableau[:-1, -1])
optimal_variables = np.zeros(n_vars)
for i in range(n_vars):
if Tableau[0, i] == optimal_solution:
optimal_variables[i] = 1
# print the optimal solution
print("Optimal solution:")
print("x =", optimal_variables[0])
print("y =", optimal_variables[1])
print("Optimal value of Z =", optimal_solution)
ii. Write a Python program to solve the following LPP:
Max Z = 2x + 4y
subject to 2x + y ≤ 18
2x + 2y ≥ 30
x + 2y = 26
x ≥ 0, y ≥ 0.
import numpy as np
# objective function coefficients
c = np.array([2, 4])
# constraint coefficients
A = np.array([[2, 1], [2, 2], [1, 2], [1, 0], [0, 1]])
b = np.array([18, 30, 26, 0, 0])
# number of variables and constraints
n_vars = c.shape[0]
n_constraints = b.shape[0]
# introduce slack and surplus variables
Slack_variables = np.zeros(n_constraints - 2)
Surplus_variable = np.zeros(1)
Artificial_variables = np.append(Slack_variables, Surplus_variable)
b = np.append(b[:-2], [26, 0])
A = np.vstack((A, np.hstack((np.zeros((2, n_vars)), Artificial_variables.reshape((2, 1))))))
# initialize the simplex tableau
Tableau = np.zeros((n_constraints + 1, n_vars + n_constraints))
for i in range(n_constraints):
for j in range(n_vars):
Tableau[i, j] = A[i, j]
Tableau[i, n_vars + i] = b[i]
Tableau[n_constraints, :n_vars] = c
# apply the simplex method
while np.any(Tableau[-1, :n_vars] < 0):
# find the entering variable
entering_var_index = np.argmin(Tableau[-1, :n_vars])
entering_var = entering_var_index + 1
# find the leaving variable
leaving_var_index = np.where(Tableau[:, entering_var_index] > 0)[0][0]
leaving_var = leaving_var_index + 1
# pivot on the entering variable
pivot_element = Tableau[leaving_var_index, entering_var_index]
for j in range(n_vars + n_constraints):
Tableau[leaving_var_index, j] /= pivot_element
for i in range(n_constraints + 1):
if i != leaving_var_index:
factor = Tableau[i, entering_var_index]
for j in range(n_vars + n_constraints):
Tableau[i, j] -= factor * Tableau[leaving_var_index, j]
# find the optimal solution
optimal_solution = np.max(Tableau[:-1, -1])
optimal_variables = np.zeros(n_vars)
for i in range(n_vars):
if Tableau[0, i] == optimal_solution:
optimal_variables[i] = 1
# print the optimal solution
print("Optimal solution:")
print("x =", optimal_variables[0])
print("y =", optimal_variables[1])
print("Optimal value of Z =", optimal_solution)
40
(b) Attempt any ONE of the following. [8]
i. Apply the following transformations on the point P [−2, 4].
I. Reflection through line 3x + 4y = 5.
II. Scaling in X coordinate by factor 6.
III. Scaling in Y coordinate by factor 4.1.
IV. Reflection through line y = 2x + 3.
def reflect_through_line(x, y, a, b, c):
# Calculate the slope of the line
m = -a / b
# Calculate the slope of the perpendicular line
m_perp = -1 / m
# Calculate the midpoint of the line segment
x_mid = (x + ((b * (b * x - a * y - c)) / (a**2 + b**2))) / 2
y_mid = (y + ((a * (b * x - a * y - c)) / (a**2 + b**2))) / 2
# Calculate the reflection
x_reflect = 2 * x_mid - x
y_reflect = 2 * y_mid - y
return x_reflect, y_reflect
def scale_x(x, factor):
return x * factor
def scale_y(y, factor):
return y * factor
# Initial point P
x, y = -2, 4
# I. Reflection through line 3x + 4y = 5
x, y = reflect_through_line(x, y, 3, 4, -5)
print("After reflection through line 3x + 4y = 5:", x, y)
# II. Scaling in X coordinate by factor 6
x = scale_x(x, 6)
print("After scaling in X coordinate by factor 6:", x, y)
# III. Scaling in Y coordinate by factor 4.1
y = scale_y(y, 4.1)
print("After scaling in Y coordinate by factor 4.1:", x, y)
# IV. Reflection through line y = 2x + 3
x, y = reflect_through_line(x, y, -2, 1, -3)
print("After reflection through line y = 2x + 3:", x, y)
ii. Apply the following transformations on the point P [−2, 4].
I. Shearing in Y direction by 7 units.
II. Scaling in both X and Y direction by 4 and 7 units respectively.
III. Rotation about origin by an angle 48 degrees.
IV. Reflection through line y = x.
import math
def shear_y(x, y, factor):
return x + factor * y
def scale(x, y, x_factor, y_factor):
return x * x_factor, y * y_factor
def rotate(x, y, angle):
angle_rad = math.radians(angle)
x_new = x * math.cos(angle_rad) - y * math.sin(angle_rad)
y_new = x * math.sin(angle_rad) + y * math.cos(angle_rad)
return x_new, y_new
def reflect_through_line_y_equals_x(x, y):
return y, x
# Initial point P
x, y = -2, 4
# I. Shearing in Y direction by 7 units
x, y = shear_y(x, y, 7)
print("After shearing in Y direction by 7 units:", x, y)
# II. Scaling in both X and Y direction by 4 and 7 units respectively
x, y = scale(x, y, 4, 7)
print("After scaling in both X and Y direction by 4 and 7 units respectively:", x, y)
# III. Rotation about origin by an angle 48 degrees
x, y = rotate(x, y, 48)
print("After rotation about origin by an angle 48 degrees:", x, y)
# IV. Reflection through line y = x
x, y = reflect_through_line_y_equals_x(x, y)
print("After reflection through line y = x:", x, y)
41
SAVITRIBAI PHULE PUNE UNIVERSITY, PUNE Board of Studies in Mathematics S.Y.B.Sc (Computer
Science) Practical Examination in Mathematics MTC-243: Python Programming Language-II (CBCS 2019
Pattern)(Semester-IV)
Slip No. : 22
Time: 3 Hours Max. Marks: 35
Q.1 Attempt any TWO of the following. [10]
(a) Write a python program to draw 2D plot y = log(x2) + sin(x) with suitable label in the x axis , y
axis and a title in [−5π, 5π].
import numpy as np
import matplotlib.pyplot as plt
# Define the range of x values
x = np.linspace(-5*np.pi, 5*np.pi, 1000)
# Calculate the y values for each x value
y = np.log(x**2) + np.sin(x)
# Create the plot
plt.plot(x, y)
# Set the labels for the x and y axes
plt.xlabel('x-axis')
plt.ylabel('y-axis')
# Set the title of the plot
plt.title('Plot of y = log(x^2) + sin(x) in the range of [-5π, 5π]')
# Display the plot
plt.show()
(b) Write a python program to Plot 3D dimensional Contour plot of parabola z = x 2 + y2, −6 < x, y <
6.
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# Define the range of x and y values
x = np.linspace(-6, 6, 100)
y = np.linspace(-6, 6, 100)
# Create a meshgrid of x and y values
X, Y = np.meshgrid(x, y)
# Calculate the z values for each x and y value
Z = X**2 + Y**2
# Create the 3D plot
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# Plot the contour plot
ax.contour(X, Y, Z)
# Set the labels for the x, y, and z axes
ax.set_xlabel('x-axis')
ax.set_ylabel('y-axis')
ax.set_zlabel('z-axis')
# Set the title of the plot
ax.set_title('3D Contour Plot of Parabola z = x^2 + y^2, -6 < x, y < 6')
# Display the plot
plt.show()
(c) Write a python program to draw 2D plot y = x sin( x12 ) in [−5, 5] with suitable label in the x axis,
y axis, a title and location of legend to lower right corner.
import numpy as np
import matplotlib.pyplot as plt
# Define the range of x values
x = np.linspace(-5, 5, 1000)
# Calculate the y values for each x value
y = x * np.sin(x**(1/2))
# Create the plot
plt.plot(x, y)
# Set the labels for the x and y axes
plt.xlabel('x-axis')
plt.ylabel('y-axis')
# Set the title of the plot
plt.title('Plot of y = x sin(x^(1/2)) in the range of [-5, 5]')
# Add a legend in the lower right corner
plt.legend(loc='lower right')
# Display the plot
plt.show()
Q.2 Attempt any TWO of the following. [10]
(a) Write a python program to find the angle at each vertices of the triangle ABC where A[0, 0], B[2,
2] and C[0, 2].
import math
# Define the coordinates of the vertices
A = (0, 0)
B = (2, 2)
C = (0, 2)
# Calculate the lengths of the sides of the triangle
a = math.sqrt((B[0] - C[0])**2 + (B[1] - C[1])**2)
b = math.sqrt((C[0] - A[0])**2 + (C[1] - A[1])**2)
c = math.sqrt((A[0] - B[0])**2 + (A[1] - B[1])**2)
# Calculate the angles using the cosine rule
angle_A = math.acos((b**2 + c**2 - a**2) / (2 * b * c))
angle_B = math.acos((a**2 + c**2 - b**2) / (2 * a * c))
angle_C = math.acos((a**2 + b**2 - c**2) / (2 * a * b))
# Print the angles in degrees
print("Angle at vertex A: {:.2f} degrees".format(angle_A * 180 / math.pi))
print("Angle at vertex B: {:.2f} degrees".format(angle_B * 180 / math.pi))
print("Angle at vertex C: {:.2f} degrees".format(angle_C * 180 / math.pi))
(b) Write a Python program to Reflect the Point P [3, 6] through the line x − 2y + 4 = 0.
# No original code provided, so I'll write a basic implementation
def reflect_point(point, line):
# Calculate the slope of the line
m = -1 / 2 # from the given equation x - 2y + 4 = 0
# Calculate the y-intercept of the line
b = 4 / 2 # from the given equation x - 2y + 4 = 0
# Calculate the slope of the perpendicular line
m_perp = -1 / m
# Calculate the midpoint of the point and its reflection
mid_x = point[0]
mid_y = point[1] - (point[0] - (b - 2 * point[1]) / m) / m_perp
# Calculate the reflection of the point
ref_x = 2 * mid_x - point[0]
ref_y = 2 * mid_y - point[1]
return [ref_x, ref_y]
point_p = [3, 6]
print("Reflection of point P", point_p, "through the line x - 2y + 4 = 0 is", reflect_point(point_p,
None))
(c) Write a Python program to find area and perimeter of the triangle ABC where A[0, 0], B[5, 0], C[3, 3].
# No original code provided, so I'll write a basic implementation
def calculate_distance(point1, point2):
return ((point1[0] - point2[0]) ** 2 + (point1[1] - point2[1]) ** 2) ** 0.5
def calculate_perimeter(point1, point2, point3):
side1 = calculate_distance(point1, point2)
side2 = calculate_distance(point2, point3)
side3 = calculate_distance(point3, point1)
return side1 + side2 + side3
def calculate_area(point1, point2, point3):
side1 = calculate_distance(point1, point2)
side2 = calculate_distance(point2, point3)
side3 = calculate_distance(point3, point1)
# Calculate semi-perimeter
s = (side1 + side2 + side3) / 2
# Calculate area using Heron's formula
return (s * (s - side1) * (s - side2) * (s - side3)) ** 0.5
point_a = [0, 0]
point_b = [5, 0]
point_c = [3, 3]
perimeter = calculate_perimeter(point_a, point_b, point_c)
area = calculate_area(point_a, point_b, point_c)
print("Perimeter of triangle ABC:", perimeter)
print("Area of triangle ABC:", area)
Q.3 Attempt the following.
(a) Attempt any ONE of the following. [7]
i. Write a Python program to solve the following LPP:
Max Z = 4x + y + 3z + 5w
subject to 4x + 6y − 5z − 4w ≥ −20
−3x − 2y + 4z + w ≤ 10
−8x − 3y + 3z + 2w ≤ 20
x, y, z, w ≥ 0.
import pulp
# Define the problem
prob = pulp.LpProblem("LPP_Problem", pulp.LpMaximize)
# Define the decision variables
x = pulp.LpVariable("x", lowBound=0)
y = pulp.LpVariable("y", lowBound=0)
z = pulp.LpVariable("z", lowBound=0)
w = pulp.LpVariable("w", lowBound=0)
# Add the objective function
prob += 4 * x + y + 3 * z + 5 * w
# Add the constraints
prob += 4 * x + 6 * y - 5 * z - 4 * w >= -20
prob += -3 * x - 2 * y + 4 * z + w <= 10
prob += -8 * x - 3 * y + 3 * z + 2 * w <= 20
# Solve the problem
prob.solve()
# Print the solution
print("Status:", pulp.LpStatus[prob.status])
print("Optimal values:")
print("x =", x.varValue)
print("y =", y.varValue)
print("z =", z.varValue)
print("w =", w.varValue)
print("Maximum value of Z =", pulp.value(prob.objective))
ii. Write a Python program to solve the following LPP:
Min Z = x + y
subject to x + y ≤ 11
x≥6
y≥6
x ≥ 0, y ≥ 0.
import pulp
# Define the problem
prob = pulp.LpProblem("LPP_Problem", pulp.LpMinimize)
# Define the decision variables
x = pulp.LpVariable("x", lowBound=0)
y = pulp.LpVariable("y", lowBound=0)
# Add the objective function
prob += x + y
# Add the constraints
prob += x + y <= 11
prob += x >= 6
prob += y >= 6
# Solve the problem
prob.solve()
# Print the solution
print("Status:", pulp.LpStatus[prob.status])
print("Optimal values:")
print("x =", x.varValue)
print("y =", y.varValue)
print("Minimum value of Z =", pulp.value(prob.objective))
42
(b) Attempt any ONE of the following. [8]
i. Write the Python program for each of the following.
I. Rotate the point (1, 1) about (1, 4) through angle π/2.
import numpy as np
def rotate_point(point, center, angle_in_radians):
rotation_matrix = np.array([[np.cos(angle_in_radians), -np.sin(angle_in_radians)],
[np.sin(angle_in_radians), np.cos(angle_in_radians)]])
point_difference = point - center
rotated_point = np.dot(rotation_matrix, point_difference) + center
return rotated_point
point = np.array((1, 1))
center = np.array((1, 4))
angle_in_radians = np.pi / 2
rotated_point = rotate_point(point, center, angle_in_radians)
print("Rotated point:", rotated_point)
II. Find Distance Between two points (0, 0) and (1, 0)
def euclidean_distance(point1, point2):
return np.sqrt(np.sum((point1 - point2) ** 2))
point1 = np.array((0, 0))
point2 = np.array((1, 0))
distance = euclidean_distance(point1, point2)
print("Distance:", distance)
III. Find the shearing of the point (3, 4) in X direction by 3 units.
def shear_point(point, shear_factor, direction):
if direction == "x":
shearing_matrix = np.array([[1, shear_factor],
[0, 1]])
elif direction == "y":
shearing_matrix = np.array([[1, 0],
[shear_factor, 1]])
else:
raise ValueError("Invalid direction. Choose 'x' or 'y'.")
sheared_point = np.dot(shearing_matrix, point)
return sheared_point
point = np.array((3, 4))
shear_factor = 3
direction = "x"
sheared_point = shear_point(point, shear_factor, direction)
print("Sheared point:", sheared_point)
IV. Represent two dimensional points using point function (−2, 5).
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return f"({self.x}, {self.y})"
point = Point(-2, 5)
print("Point:", point)
ii. A Company has 3 production facilities S1, S2 and S3 with production capacity of 7, 9 and
18 units (in 100’s) per week of a product, respectively. These units are to be shipped to 4
warehouses D1, D2, D3 and D4 with requirement of 5, 6, 7 and 14 units (in 100’s) per week,
respectively. The transportation costs (in rupees) per unit between factories to warehouses
are given in the table below.
D1 D2 D3 D4 Supply
S1 19 30 50 10 7
S2 70 30 40 60 9
S3 40 8 70 20 18
Demand 5 8 7 14 34
Write a Python programme to solve transportation problem for minimize the costs of whole
operation.
import pulp
# Define the supply and demand data
supply = {
'S1': 7,
'S2': 9,
'S3': 18,
}
demand = {
'D1': 5,
'D2': 8,
'D3': 7,
'D4': 14,
}
cost_matrix = {
('S1', 'D1'): 19, ('S1', 'D2'): 30, ('S1', 'D3'): 50, ('S1', 'D4'): 10,
('S2', 'D1'): 70, ('S2', 'D2'): 30, ('S2', 'D3'): 40, ('S2', 'D4'): 60,
('S3', 'D1'): 40, ('S3', 'D2'): 8, ('S3', 'D3'): 70, ('S3', 'D4'): 20,
}
# Create the problem
prob = pulp.LpProblem("Transportation_Problem", pulp.LpMinimize)
# Create the decision variables
transportation = pulp.LpVariable.dicts("Transportation", ((i, j) for i in supply for j in demand), lowBound=0,
cat='Continuous')
# Add the objective function
prob += pulp.lpSum(transportation[i, j] * cost_matrix[i, j] for i in supply for j in demand), "Total_Cost"
# Add supply constraints
for i in supply:
prob += pulp.lpSum(transportation[i, j] for j in demand) == supply[i]
# Add demand constraints
for j in demand:
prob += pulp.lpSum(transportation[i, j] for i in supply) == demand[j]
# Solve the problem
prob.solve()
# Print the solution
print("Status:", pulp.LpStatus[prob.status])
print("Total Cost:", pulp.value(prob.objective))
for i in supply:
for j in demand:
if transportation[i, j].varValue > 0:
print(f"{i} -> {j}: {transportation[i, j].varValue:.2f} units")
43
SAVITRIBAI PHULE PUNE UNIVERSITY, PUNE Board of Studies in Mathematics S.Y.B.Sc (Computer
Science) Practical Examination in Mathematics MTC-243: Python Programming Language-II (CBCS 2019
Pattern)(Semester-IV)
Slip No. : 23
Time: 3 Hours Max. Marks: 35
Q.1 Attempt any TWO of the following. [10]
(a) Write a python program plot the graphs of sin x,and cos x in [0, π] in one figure with 2×1 subplots.
import numpy as np
import matplotlib.pyplot as plt
# Create the x range
x = np.linspace(0, np.pi, 100)
# Create the subplots
fig, ax = plt.subplots(2, 1, figsize=(8, 6))
# Plot sin(x)
ax[0].plot(x, np.sin(x))
ax[0].set_title('sin(x)')
ax[0].grid(True)
# Plot cos(x)
ax[1].plot(x, np.cos(x))
ax[1].set_title('cos(x)')
ax[1].grid(True)
# Show the plot
plt.show()
(b) Write a python program to Plot the graph of the following functions in the given interval.
i. f(x) = x3 in [0, 5].
ii. f(x) = x2 in [−2, 2].
import numpy as np
import matplotlib.pyplot as plt
# Function 1: f(x) = x^3 in [0, 5]
x1 = np.linspace(0, 5, 100)
y1 = x1**3
plt.plot(x1, y1, label='f(x) = x^3')
# Function 2: f(x) = x^2 in [-2, 2]
x2 = np.linspace(-2, 2, 100)
y2 = x2**2
plt.plot(x2, y2, label='f(x) = x^2')
plt.xlabel('x')
plt.ylabel('f(x)')
plt.title('Graphs of f(x) = x^3 and f(x) = x^2')
plt.legend()
plt.show()
(c) Write a python program to plot 3D Surface Plot of the function z = cos(|x|+ |y|) in −1 < x, y < 1.
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# Create a grid of x and y values
x = np.linspace(-1, 1, 20)
y = np.linspace(-1, 1, 20)
X, Y = np.meshgrid(x, y)
# Calculate the z-values for each (x, y) pair
Z = np.cos(np.abs(X) + np.abs(Y))
# Create a 3D plot
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# Plot the surface
ax.plot_surface(X, Y, Z, cmap='viridis')
# Set the limits of the plot
ax.set_xlim(-1, 1)
ax.set_ylim(-1, 1)
ax.set_zlim(-1, 1)
# Set the labels of the axes
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')
# Show the plot
plt.show()
Q.2 Attempt any TWO of the following. [10]
(a) Write a Python program to draw regular polygon with 20 sides and radius 1 centered at (0, 0).
import matplotlib.pyplot as plt
# Create a figure and a set of subplots
fig, ax = plt.subplots()
# Set the limits of the plot
ax.set_xlim(-1.5, 1.5)
ax.set_ylim(-1.5, 1.5)
# Create a regular polygon with 20 sides and radius 1
theta = np.linspace(0, 2 * np.pi, 20)
x = np.cos(theta)
y = np.sin(theta)
# Plot the polygon
ax.plot(x, y, 'bo-')
# Show the plot
plt.show()
(b) Write a Python program to draw a polygon with vertices (0, 0), (1, 0), (2, 2), (1, 4). Also find area
of polygon.
import matplotlib.pyplot as plt
from shapely.geometry import Polygon
# Create a figure and a set of subplots
fig, ax = plt.subplots()
# Set the limits of the plot
ax.set_xlim(0, 2.5)
ax.set_ylim(0, 5)
# Create a list of vertices
vertices = [(0, 0), (1, 0), (2, 2), (1, 4)]
# Create a Polygon object from the vertices
polygon = Polygon(vertices)
# Calculate the area of the polygon
area = polygon.area
# Plot the polygon
ax.plot(*polygon.exterior.coords.xy, 'ro-')
# Add the area of the polygon to the plot
ax.text(0.5, 0.5, f"Area: {area:.2f}", transform=ax.transAxes)
# Show the plot
plt.show()
(c) Write a Python program to find area and perimeter of triangle ABC where A[0, 1], B[−5, 0] and
C[−3, 3].
import math
# Define the vertices of the triangle
A = [0, 1]
B = [-5, 0]
C = [-3, 3]
# Find the length of the sides using the distance formula
a = math.sqrt((B[0] - C[0])**2 + (B[1] - C[1])**2)
b = math.sqrt((A[0] - C[0])**2 + (A[1] - C[1])**2)
c = math.sqrt((A[0] - B[0])**2 + (A[1] - B[1])**2)
# Find the semi-perimeter of the triangle
s = (a + b + c) / 2
# Find the area of the triangle using Heron's formula
area = math.sqrt(s * (s - a) * (s - b) * (s - c))
# Find the perimeter of the triangle
perimeter = a + b + c
# Print the results
print("Area of the triangle: ", area)
print("Perimeter of the triangle: ", perimeter)
Q.3 Attempt the following.
(a) Attempt any ONE of the following. [7]
i. Write a Python program to solve the following LPP:
Max Z = 3x + 5y + 4z
subject to 2x + 3y ≤ 8
2x + 5y ≤ 10
3x + 2y + 4z ≤ 15
x, y, z ≥ 0.
import numpy as np
from scipy.optimize import linprog
# Define the objective function
c = np.array([3, 5, 4])
# Define the constraints
A_ub = np.array([[2, 3, 0],
[2, 5, 0],
[3, 2, 4]])
b_ub = np.array([8, 10, 15])
# Define the bounds
bounds = [(0, None), (0, None), (0, None)]
# Define the options
options = {'disp': True}
# Solve the LPP
res = linprog(c, A_ub=A_ub, b_ub=b_ub, bounds=bounds,
options=options)
# Print the results
print("Optimal solution found:")
print("x = ", res.x[0])
print("y = ", res.x[1])
print("z = ", res.x[2])
print("Maximum value of Z = ", res.fun)
ii. Write a Python program to solve the following LPP:
Min Z = 3x + 5y + 4z
subject to 2x + 2y ≤ 12
2x + 2y ≤ 10
5x + 2y ≤ 10
x ≥ 0, y ≥ 0.
import numpy as np
from scipy.optimize import linprog
# Define the objective function
c = np.array([3, 5, 4])
# Define the constraints
A_ub = np.array([[2, 3, 0],
[2, 5, 0],
[3, 2, 4]])
b_ub = np.array([8, 10, 15])
# Define the bounds
bounds = [(0, None), (0, None), (0, None)]
# Define the options
options = {'disp': True}
# Solve the LPP
res = linprog(c, A_ub=A_ub, b_ub=b_ub, bounds=bounds, options=options)
# Print the results
print("Optimal solution found:")
print("x = ", res.x[0])
print("y = ", res.x[1])
print("z = ", res.x[2])
print("Maximum value of Z = ", res.fun)
44
(b) Attempt any ONE of the following. [8]
i. Write the Python program to apply each of the following transformation on the point P = [3,
−1].
I. Reflection through X axis.
P = [3, -1]
P_reflected = [P[0], -P[1]]
print(P_reflected) # Output: [3, 1]
II. Rotation about origin by an angle 30 degrees.
import math
P = [3, -1]
angle = math.radians(30) # Convert degree to radians
rotation_matrix = [
[math.cos(angle), -math.sin(angle)],
[math.sin(angle), math.cos(angle)]
]
P_rotated = [
sum(x * y for x, y in zip(rotation_matrix[i], P))
for i in range(2)
]
print(P_rotated) # Output: [2.598076211353316, -2.3431457059272746]
III. Scaling in Y coordinate by factor 8.
P = [3, -1]
scale_factor = 8
P_scaled = [P[0], P[1] * scale_factor]
print(P_scaled) # Output: [3, -8]
IV. Shearing in X direction by 2 units.
P = [3, -1]
shear_factor = 2
shearing_matrix = [
[1, shear_factor],
[0, 1]
]
P_sheared = [
sum(x * y for x, y in zip(shearing_matrix[i], P))
for i in range(2)
]
print(P_sheared) # Output: [5, -1]
ii. Write a Python program to apply each of the following transformations on the point P [−2, 4].
I. Reflection through the line y = x + 2.
P = [-2, 4]
m=1
x0 = -2
P_reflected = [P[0], P[1] - 2 * m * (P[0] - x0)]
print(P_reflected) # Output: [-2, 6]
II. Scaling in Y -coordinate by factor 2.
P = [-2, 4]
scale_factor = 2
P_scaled = [P[0], P[1] * scale_factor]
print(P_scaled) # Output: [-2, 8]
III. Shearing in X direction by 4 units.
P = [-2, 4]
shear_factor = 4
P_sheared = [P[0] + shear_factor * P[1], P[1]]
print(P_sheared) # Output: [18, 4]
IV. Rotation about origin by an angle 60 degrees.
import math
P = [-2, 4]
angle = math.radians(60) # Convert degree to radians
rotation_matrix = [
[math.cos(angle), -math.sin(angle)],
[math.sin(angle), math.cos(angle)]
]
P_rotated = [
sum(x * y for x, y in zip(rotation_matrix[i], P))
for i in range(2)
]
print(P_rotated) # Output: [-1.7320508075688772, 3.4641016151377544]
45
SAVITRIBAI PHULE PUNE UNIVERSITY, PUNE Board of Studies in Mathematics S.Y.B.Sc (Computer
Science) Practical Examination in Mathematics MTC-243: Python Programming Language-II (CBCS 2019
Pattern)(Semester-IV)
Slip No. : 24
Time: 3 Hours Max. Marks: 35
Q.1 Attempt any TWO of the following. [10]
(a) Write a Python program to plot 3D graph of the function f(x) = e−x2 in [−5, 5] with green dashed
points line with upward pointing triangle.
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# Define the function
def f(x):
return np.exp(-x**2)
# Create a range of x values from -5 to 5
x = np.linspace(-5, 5, 100)
# Create a meshgrid of x and y values
X, Y = np.meshgrid(x, x)
# Calculate the z values using the function
Z = f(X)
# Create a 3D plot
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# Plot the surface
ax.plot_surface(X, Y, Z, cmap='viridis', alpha=0.5)
# Define the point for the triangle
point = np.array([0, 0, f(0)])
# Define the vertices of the triangle
vertices = np.array([[-1, 0, f(-1)], [1, 0, f(1)], point])
# Plot the triangle
ax.plot(vertices[:, 0], vertices[:, 1], vertices[:, 2], 'g-^', markersize=10)
# Plot the dashed points
ax.plot(x, f(x), 'go', markersize=5, linestyle='--')
# Set the axis labels
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
# Set the title
ax.set_title('3D Graph of f(x) = e^-x^2 in [-5, 5] with Green Dashed Points and Upward Pointing
Triangles')
# Show the plot
plt.show()
(b) Write the Python program to plot the graph of the function, using def()
import numpy as np
import matplotlib.pyplot as plt
def f(x):
if x < 5:
return x**2 + 4
else:
return 3*x + 9
x = np.linspace(-10, 10, 400)
y = [f(i) for i in x]
plt.plot(x, y)
plt.xlabel('x')
plt.ylabel('f(x)')
plt.title('Graph of f(x)')
plt.grid(True)
plt.show()
f(x) = x2 + 4 if −10 ≤ x < 5
3x + 9 if 5 ≤ x < 10
(c) Write a Python program to plot graph of the function f(x) = log(3x 2), in [1, 10] with black dashed
points.
import numpy as np
import matplotlib.pyplot as plt
def f(x):
return np.log(3*x**2)
x = np.linspace(1, 10, 400)
y = f(x)
plt.plot(x, y, 'k--')
plt.xlabel('x')
plt.ylabel('f(x)')
plt.title('Graph of f(x) = log(3x2)')
plt.grid(True)
plt.show()
Q.2 Attempt any TWO of the following. [10]
(a) Write a python program to plot triangle with vertices [3, 3], [5, 6], [5, 2], and its rotation about the
origin by angle −π radians.
import matplotlib.pyplot as plt
import numpy as np
# Define the vertices of the triangle
vertices = np.array([[3, 3], [5, 6], [5, 2]])
# Plot the triangle
plt.plot(vertices[:, 0], vertices[:, 1], 'bo-')
# Rotate the triangle about the origin by -π radians
rotation_matrix = np.array([[np.cos(-np.pi), -np.sin(-np.pi)],
[np.sin(-np.pi), np.cos(-np.pi)]])
rotated_vertices = np.dot(rotation_matrix, vertices.T).T
# Plot the rotated triangle
plt.plot(rotated_vertices[:, 0], rotated_vertices[:, 1], 'ro-')
# Add labels and title
plt.xlabel('x')
plt.ylabel('y')
plt.title('Triangle and its rotation about the origin by -π radians')
# Show the plot
plt.show()
(b) Write a Python program to generate vector x in the interval [−22, 22] using numpy package with
80 subintervals.
import numpy as np
x = np.linspace(-22, 22, 81)
print(x)
(c) Write a Python program to draw a polygon with vertices (0, 0), (1, 0), (2, 2), (1, 4). Also find area
and perimeter of the polygon.
import matplotlib.pyplot as plt
# Define the vertices of the polygon
vertices = [(0, 0), (1, 0), (2, 2), (1, 4)]
# Calculate the perimeter of the polygon
perimeter = sum(np.sqrt((x2 - x1)**2 + (y2 - y1)**2) for x1, y1, x2, y2 in zip(vertices, vertices[1:]
+ [vertices[0]]))
# Calculate the area of the polygon using the shoelace formula
area = 0.5 * np.abs(sum(x1*y2 - x2*y1 for x1, y1, x2, y2 in zip(vertices, vertices[1:] +
[vertices[0]])))
# Plot the polygon
plt.plot(*zip(*vertices), 'o-')
plt.xlim(0, 3)
plt.ylim(0, 5)
plt.title('Polygon with vertices (0, 0), (1, 0), (2, 2), (1, 4)')
plt.xlabel('x')
plt.ylabel('y')
# Display the plot
plt.show()
# Print the perimeter and area
print(f'Perimeter: {perimeter:.2f}')
print(f'Area: {area:.2f}')
Q.3 Attempt the following.
(a) Attempt any ONE of the following. [7]
i. Write a Python program to solve the following LPP:
Min Z = 3.5x + 2y
subject to x + y ≥ 5
x≥4
y≤2
x ≥ 0, y ≥ 0.
import numpy as np
from scipy.optimize import linprog
# Define the objective function
c = np.array([3.5, 2])
# Define the constraints
A_ub = np.array([[1, 1], [1, 0], [0, 1], [-1, 0], [0, -1]])
b_ub = np.array([5, 4, 2, 0, 0])
# Define the bounds
bounds = [(0, None), (0, None)]
# Define the options
options = {'disp': True}
# Solve the LPP
res = linprog(c, A_ub=A_ub, b_ub=b_ub, bounds=bounds, options=options)
# Print the solution
print(f"The optimal value of Z is {res.fun:.2f} at the point ({res.x[0]:.2f}, {res.x[1]:.2f})")
ii. Write a Python program to solve the following LPP:
Min Z = x + y
subject to x ≥ 6
y≥6
x + y ≤ 11
x ≥ 0, y ≥ 0.
import numpy as np
from scipy.optimize import linprog
# Define the objective function
c = np.array([1, 1])
# Define the constraints
A_ub = np.array([[1, 1], [1, 0], [0, 1]])
b_ub = np.array([11, 6, 6])
A_eq = np.array([[1, 1]])
b_eq = np.array([6])
# Define the bounds
bounds = [(0, None), (0, None)]
# Define the options
options = {'disp': True}
# Solve the LPP
res = linprog(c, A_ub=A_ub, b_ub=b_ub, A_eq=A_eq, b_eq=b_eq, bounds=bounds, options=options)
# Print the solution
print(f"The optimal value of Z is {res.fun:.2f} at the point ({res.x[0]:.2f}, {res.x[1]:.2f})")
46
(b) Attempt any ONE of the following. [8]
i. Apply Python program in each of the following transformations on the point P [3, −1]
I. Refection through X−axis.
II. Scaling in X−coordinate by factor 2.
III. Scaling in Y−coordinate by factor 1.5.
IV. Reflection through the line y = x.
class Point:
""" Point class for representing and manipulating x,y coordinates. """
def __init__(self, initX, initY):
self.x = initX
self.y = initY
def __str__(self):
return str(self.x)+","+str(self.y)
# method reflect_x to Point which returns a new Point, one which is the reflection of the
point about the x-axis
def reflect_x(self):
x1 = self.x
y1 = (-1)*self.y
return Point(x1, y1)
# method scale_x to Point which returns a new Point, one which is the scaling of the
point in x-coordinate by factor 2
def scale_x(self, factor):
x1 = self.x * factor
y1 = self.y
return Point(x1, y1)
# method scale_y to Point which returns a new Point, one which is the scaling of the
point in y-coordinate by factor 1.5
def scale_y(self, factor):
x1 = self.x
y1 = self.y * factor
return Point(x1, y1)
# method reflect_yx to Point which returns a new Point, one which is the reflection of the
point through the line y = x
def reflect_yx(self):
x1 = self.y
y1 = self.x
return Point(x1, y1)
# create a Point object with coordinates [3, -1]
P = Point(3, -1)
# apply the transformations
P_reflected_x = P.reflect_x()
P_scaled_x = P.scale_x(2)
P_scaled_y = P.scale_y(1.5)
P_reflected_yx = P.reflect_yx()
# print the results
print("I. Reflection through X-axis: ", P_reflected_x)
print("II. Scaling in X-coordinate by factor 2: ", P_scaled_x)
print("III. Scaling in Y-coordinate by factor 1.5: ", P_scaled_y)
print("IV. Reflection through the line y = x: ", P_reflected_yx)
ii. Find the combined transformation of the line segment between the points A[4, −1] & B[3, 0]
by using Python program for the following sequence of transformations:-
I. Rotation about origin through an angle π.
II. Shearing in Y direction by 4.5 units.
III. Scaling in X− coordinate by 3 units.
IV. Reflection through the line y = x.
import math
class Point:
""" Point class for representing and manipulating x,y coordinates. """
def __init__(self, initX, initY):
self.x = initX
self.y = initY
def __str__(self):
return str(self.x)+","+str(self.y)
# method rotate to Point which returns a new Point, one which is the rotation of the point
about the origin through an angle pi
def rotate(self):
x1 = self.x * math.cos(math.pi) - self.y * math.sin(math.pi)
y1 = self.x * math.sin(math.pi) + self.y * math.cos(math.pi)
return Point(x1, y1)
# method shear_y to Point which returns a new Point, one which is the shearing of the
point in y-direction by 4.5 units
def shear_y(self):
x1 = self.x
y1 = self.y + 4.5 * self.x
return Point(x1, y1)
# method scale_x to Point which returns a new Point, one which is the scaling of the
point in x-coordinate by factor 3
def scale_x(self, factor):
x1 = self.x * factor
y1 = self.y
return Point(x1, y1)
# method reflect_yx to Point which returns a new Point, one which is the reflection of the
point through the line y = x
def reflect_yx(self):
x1 = self.y
y1 = self.x
return Point(x1, y1)
# create Point objects for A and B
A = Point(4, -1)
B = Point(3, 0)
# apply the transformations
A_rotated = A.rotate()
B_rotated = B.rotate()
A_sheared = A_rotated.shear_y()
B_sheared = B_rotated.shear_y()
A_scaled = A_sheared.scale_x(3)
B_scaled = B_sheared.scale_x(3)
A_reflected = A_scaled.reflect_yx()
B_reflected = B_scaled.reflect_yx()
# print the results
print("A after I. Rotation about origin through an angle pi: ", A_rotated)
print("B after I. Rotation about origin through an angle pi: ", B_rotated)
print("A after II. Shearing in Y direction by 4.5 units: ", A_sheared)
print("B after II. Shearing in Y direction by 4.5 units: ", B_sheared)
print("A after III. Scaling in X-coordinate by factor 3: ", A_scaled)
print("B after III. Scaling in X-coordinate by factor 3: ", B_scaled)
print("A after IV. Reflection through the line y = x: ", A_reflected)
print("B after IV. Reflection through the line y = x: ", B_reflected)
47
SAVITRIBAI PHULE PUNE UNIVERSITY, PUNE Board of Studies in Mathematics S.Y.B.Sc (Computer
Science) Practical Examination in Mathematics MTC-243: Python Programming Language-II (CBCS 2019
Pattern)(Semester-IV)
Slip No. : 25
Time: 3 Hours Max. Marks: 35
Q.1 Attempt any TWO of the following. [10]
(a) Write a Python program to generate 3D plot of the functions z = sin x + cos y in −10 < x, y < 10.
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# create a grid of x and y values
x = np.linspace(-10, 10, 100)
y = np.linspace(-10, 10, 100)
X, Y = np.meshgrid(x, y)
# calculate the z values
Z = np.sin(X) + np.cos(Y)
# create a 3D plot
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# plot the surface
ax.plot_surface(X, Y, Z, cmap='viridis')
# set the limits of the plot
ax.set_xlim(-10, 10)
ax.set_ylim(-10, 10)
ax.set_zlim(-10, 10)
# show the plot
plt.show()
(b) Using Python plot the graph of function f(x) = sin−1(x) on the interval [−1, 1].
import numpy as np
import matplotlib.pyplot as plt
# create a grid of x values
x = np.linspace(-1, 1, 100)
# calculate the y values
y = np.arcsin(x)
# create a plot
plt.plot(x, y)
# set the limits of the plot
plt.xlim(-1, 1)
plt.ylim(-np.pi/2, np.pi/2)
# set the labels of the plot
plt.xlabel('x')
plt.ylabel('sin^-1(x)')
# show the plot
plt.show()
(c) Using Python plot the surface plot of function z = cos x 2 + y2 − 0.5 in the interval from −1 <
x, y < 1.
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# create a grid of x and y values
x = np.linspace(-1, 1, 100)
y = np.linspace(-1, 1, 100)
X, Y = np.meshgrid(x, y)
# calculate the z values
Z = np.cos(X**2) + Y**2 - 0.5
# create a 3D plot
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# plot the surface
ax.plot_surface(X, Y, Z, cmap='viridis')
# set the limits of the plot
ax.set_xlim(-1, 1)
ax.set_ylim(-1, 1)
ax.set_zlim(-1, 1)
# show the plot
plt.show()
Q.2 Attempt any TWO of the following. [10]
(a) Rotate the line segment by 180◦ having end points (1, 0) and (2, −1).
def rotate_line_segment(point1, point2):
"""
Rotate a line segment by 180 degrees around the origin.
:param point1: the first point of the line segment (x1, y1)
:param point2: the second point of the line segment (x2, y2)
:return: the rotated line segment as a list of two points
"""
# Rotate the points
rotated_point1 = (-point1[0], -point1[1])
rotated_point2 = (-point2[0], -point2[1])
# Return the rotated line segment
return [rotated_point1, rotated_point2]
# Define the original line segment
line_segment = [(1, 0), (2, -1)]
# Rotate the line segment
rotated_line_segment = rotate_line_segment(line_segment[0], line_segment[1])
# Print the original and rotated line segments
print("Original line segment:", line_segment)
print("Rotated line segment:", rotated_line_segment)
(b) Using sympy, declare the points P (5, 2), Q(5, −2), R(5, 0), check whether these points are
collinear. Declare the ray passing through the points P and Q, find the length of this ray between
P and Q. Also find slope of this ray.
import sympy as sp
# Declare the points
P = sp.Point(5, 2)
Q = sp.Point(5, -2)
R = sp.Point(5, 0)
# Calculate the slopes between pairs of points
slope_PQ = (Q.y - P.y) / (Q.x - P.x)
slope_PR = (R.y - P.y) / (R.x - P.x)
# Check if the points are collinear
if slope_PQ == slope_PR:
print("The points are collinear.")
else:
print("The points are not collinear.")
# Calculate the length of the ray between P and Q
length_PQ = P.distance(Q)
# Calculate the slope of the ray
slope_PQ = (Q.y - P.y) / (Q.x - P.x)
# Print the results
print("Length of the ray between P and Q:", length_PQ)
print("Slope of the ray:", slope_PQ)
(c) Generate triangle with vertices (0, 0), (4, 0), (1, 4), check whether the triangle is Scalene triangle.
import sympy as sp
# Declare the points
A = sp.Point(0, 0)
B = sp.Point(4, 0)
C = sp.Point(1, 4)
# Calculate the distances between pairs of points
distance_AB = A.distance(B)
distance_BC = B.distance(C)
distance_CA = C.distance(A)
# Check if the triangle is a scalene triangle
if distance_AB != distance_BC and distance_BC != distance_CA and distance_CA != distance_AB:
print("The triangle is a scalene triangle.")
else:
print("The triangle is not a scalene triangle.")
# Print the distances between pairs of points
print("Distance between A and B:", distance_AB)
print("Distance between B and C:", distance_BC)
print("Distance between C and A:", distance_CA)
Q.3 Attempt the following.
(a) Attempt any ONE of the following. [7]
i. Write a Python program to solve the following LPP:
Max Z = 150x + 75y
subject to 4x + 6y ≤ 24
5x + 3y ≤ 15
x ≥ 0, y ≥ 0.
import numpy as np
from scipy.optimize import linprog
# Define the objective function
c = np.array([150, 75])
# Define the constraints
A_ub = np.array([[4, 6], [5, 3]])
b_ub = np.array([24, 15])
# Define the bounds
bounds = [(0, None), (0, None)]
# Define the options
options = {'disp': True}
# Solve the LPP
res = linprog(c, A_ub=A_ub, b_ub=b_ub, bounds=bounds, options=options)
# Print the solution
print("Optimal solution found:")
print("x =", res.x[0])
print("y =", res.x[1])
print("Maximum value of Z =", res.fun)
ii. Write a Python program to solve the following LPP:
Max Z = 4x + y + 3z + 5w
subject to 4x + 6y − 5z − 4w ≥ 20
−3x − 2y + 4z + w ≤ 10
−8x − 3y + 3z + 2w ≤ 20
x ≥ 0, y ≥ 0, z ≥ 0, w ≥ 0.
import numpy as np
from scipy.optimize import linprog
# Define the objective function
c = np.array([4, 1, 3, 5])
# Define the constraints
A_eq = np.array([[4, 6, -5, -4],
[-3, -2, 4, 1],
[-8, -3, 3, 2]])
b_eq = np.array([20, 10, 20])
# Define the bounds
bounds = [(0, None), (0, None), (0, None), (0, None)]
# Define the options
options = {'disp': True}
# Solve the LPP
res = linprog(c, A_eq=A_eq, b_eq=b_eq, bounds=bounds, options=options)
# Print the solution
print("Optimal solution found:")
print("x =", res.x[0])
print("y =", res.x[1])
print("z =", res.x[2])
print("w =", res.x[3])
print("Maximum value of Z =", res.fun)
48
(b) Attempt any ONE of the following. [8]
i. Write a python program to apply the following transformations on the point (−2, 4) :
I. Refection through X−axis.
II. Scaling in X−coordinate by factor 6.
III. Shearing in X direction by 4 units.
IV. Rotate about origin through an angle 30◦.
import math
# Define the point
point = np.array([-2, 4])
# I. Reflection through X-axis
point_reflected = np.array([point[0], -point[1]])
print("I. Reflection through X-axis:", point_reflected)
# II. Scaling in X-coordinate by factor 6
point_scaled = np.array([point[0] * 6, point[1]])
print("II. Scaling in X-coordinate by factor 6:", point_scaled)
# III. Shearing in X direction by 4 units
point_sheared = np.array([point[0] + 4 * point[1], point[1]])
print("III. Shearing in X direction by 4 units:", point_sheared)
# IV. Rotation about origin through an angle 30 degrees
angle_rad = math.radians(30)
rotation_matrix = np.array([[math.cos(angle_rad), -math.sin(angle_rad)],
[math.sin(angle_rad), math.cos(angle_rad)]])
point_rotated = np.dot(rotation_matrix, point)
print("IV. Rotation about origin through an angle 30 degrees:", point_rotated)
ii. Write a python program to find the combined transformation of the line segment between
the points A[3, 2] & B[2, −3] for the following sequence of transformations:-
I. Rotation about origin through an angle π6 .
II. Scaling in Y−coordinate by −4 units.
III. Uniform scaling by −6.4 units.
IV. Shearing in Y direction by 5 units.
import math
import numpy as np
# Define the points A and B
A = np.array([3, 2])
B = np.array([2, -3])
# I. Rotation about origin through an angle π/6
angle_rad = math.radians(30)
rotation_matrix = np.array([[math.cos(angle_rad), -math.sin(angle_rad)],
[math.sin(angle_rad), math.cos(angle_rad)]])
A_rotated = np.dot(rotation_matrix, A)
B_rotated = np.dot(rotation_matrix, B)
# II. Scaling in Y-coordinate by -4 units
A_scaled = np.array([A_rotated[0], A_rotated[1] * -4])
B_scaled = np.array([B_rotated[0], B_rotated[1] * -4])
# III. Uniform scaling by -6.4 units
A_uniform_scaled = np.array([A_scaled[0] * -6.4, A_scaled[1] * -6.4])
B_uniform_scaled = np.array([B_scaled[0] * -6.4, B_scaled[1] * -6.4])
# IV. Shearing in Y direction by 5 units
shearing_matrix = np.array([[1, 5],
[0, 1]])
A_sheared = np.dot(shearing_matrix, A_uniform_scaled)
B_sheared = np.dot(shearing_matrix, B_uniform_scaled)
# Print the transformed points A' and B'
print("Transformed points A' and B':")
print("A' =", A_sheared)
print("B' =", B_sheared)
49