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

Python Code Solutions

Uploaded by

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

Python Code Solutions

Uploaded by

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

# Python Code Solutions

# 1. Write a program in Python to swap two variables.

a=5

b = 10

a, b = b, a

print("After swapping: a =", a, "b =", b)

print("\n" + "-"*30 + "\n")

# 2. Write a program in Python to check the input character is an alphabet or not.

char = input("Enter a character: ")

if char.isalpha():

print(char, "is an alphabet.")

else:

print(char, "is not an alphabet.")

print("\n" + "-"*30 + "\n")

# 3. Write a program in Python to shuffle a deck of cards using the module random and draw 5 cards.

import random

deck = [f"{rank} of {suit}" for rank in ["2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"]

for suit in ["Hearts", "Diamonds", "Clubs", "Spades"]]

random.shuffle(deck)

print("5 drawn cards:", deck[:5])

print("\n" + "-"*30 + "\n")

# 4. Write a program in Python to find the factors of a number.

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

factors = [i for i in range(1, num + 1) if num % i == 0]

print("Factors of", num, "are:", factors)


print("\n" + "-"*30 + "\n")

# 5. Write a program in Python to transpose a given matrix M = [[1, 2], [4, 5], [3, 6]].

M = [[1, 2], [4, 5], [3, 6]]

transposed_M = [[M[j][i] for j in range(len(M))] for i in range(len(M[0]))]

print("Transposed matrix:", transposed_M)

print("\n" + "-"*30 + "\n")

# 6. Write a program in Python to print the median of a set of numbers in a file.

import statistics

with open("numbers.txt", "r") as file:

numbers = [int(line.strip()) for line in file]

median = statistics.median(numbers)

print("Median of numbers:", median)

print("\n" + "-"*30 + "\n")

# 7. Write a function in Python to find the resolution of a JPEG image.

from PIL import Image

def find_resolution(image_path):

with Image.open(image_path) as img:

return img.size

print("Resolution:", find_resolution("image.jpg"))

print("\n" + "-"*30 + "\n")

# 8. Write a program in Python to convert a decimal number to binary, octal, and hexadecimal number.

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

print("Binary:", bin(decimal))

print("Octal:", oct(decimal))

print("Hexadecimal:", hex(decimal))
print("\n" + "-"*30 + "\n")

# 9. Write a program in Python to sort words in alphabetical order.

words = input("Enter words separated by spaces: ").split()

words.sort()

print("Sorted words:", ' '.join(words))

print("\n" + "-"*30 + "\n")

# 10. Use Matplotlib to draw histogram to represent average age of population.

import matplotlib.pyplot as plt

ages = [21, 54, 66, 44, 32, 42, 54, 62, 93, 45, 32, 70]

plt.hist(ages, bins=5, color='blue', edgecolor='black')

plt.title("Histogram of Population Age")

plt.xlabel("Age")

plt.ylabel("Frequency")

plt.show()

print("\n" + "-"*30 + "\n")

# 11. Create a 3-D plot in Python for the function √(y^2 - x^2).

import numpy as np

from mpl_toolkits.mplot3d import Axes3D

x = np.linspace(-3, 3, 100)

y = np.linspace(-3, 3, 100)

X, Y = np.meshgrid(x, y)

Z = np.sqrt(Y**2 - X**2)

fig = plt.figure()

ax = fig.add_subplot(111, projection='3d')

ax.plot_surface(X, Y, Z, cmap='viridis')

plt.show()
% MATLAB Code Solutions

% 1. Given two sides a= 3.2 and b=4.6 of a triangle and angle theta= 60°.

a = 3.2;

b = 4.6;

theta = 60 * (pi / 180); % Convert degrees to radians

c = sqrt(a^2 + b^2 - 2 * a * b * cos(theta));

area = 0.5 * a * b * sin(theta);

fprintf("Third side: %.2f\n", c);

fprintf("Area of triangle: %.2f\n", area);

disp(' ');

% 2. Calculate the sum of the series: S= 1 - x^2/2! + x^4/4! - x^6/6! + x^8/8!

x = 1.5;

S = 1 - (x^2 / factorial(2)) + (x^4 / factorial(4)) - (x^6 / factorial(6)) + (x^8 / factorial(8));

fprintf("Sum of series S: %.4f\n", S);

disp(' ');

% 3. Extend the 2-D array to 3-D array by including another 2-D array as second element.

A = [1 2 3; 5 4 3; 1 3 6];

A(:,:,2) = [7 8 9; 6 5 4; 3 2 1];

disp("Extended 3-D Array A:");

disp(A);

disp(' ');

% 4. Reshape matrix A of size (3x4) into matrix B of size (6x2).

A = [1 2 3 5; 6 7 9 10; 11 4 8 12];

B = reshape(A, [6, 2]);

disp("Reshaped Matrix B:");

disp(B);
disp(' ');

% 5. Create diagonal matrix A, and matrices B and C with vector z.

z = [2; 3; 4; 5];

A = diag(z);

B = diag(z, 1);

C = diag(z, -1);

disp("Diagonal Matrix A:");

disp(A);

disp("Upper Diagonal Matrix B:");

disp(B);

disp("Lower Diagonal Matrix C:");

disp(C);

disp(' ');

% 6. Integrate the polynomial y = 4x^3 + 12x^2 + 16x + 1.

syms x;

y = 4*x^3 + 12*x^2 + 16*x + 1;

integral_y = int(y, x) + 3;

disp("Integrated Polynomial:");

disp(integral_y);

disp(' ');

% 7. Find polynomial of degree 2 to fit the data: x = [0 1 2 4], y = [1 6 20 100].

x = [0 1 2 4];

y = [1 6 20 100];

p = polyfit(x, y, 2);

disp("Fitted Polynomial Coefficients:");

disp(p);
disp(' ');

% 8. Illustrate use of `pause` command.

disp("Pausing for 3 seconds...");

pause(3);

disp("Resuming after pause.");

disp(' ');

% 9. Illustrate the use of `fwrite` for binary data.

fileID = fopen('check.txt', 'w');

fwrite(fileID, 123.45, 'float32');

fwrite(fileID, int32(567), 'int32');

fclose(fileID);

disp("Data written to 'check.txt' in binary format.");

disp(' ');

% 10. Plot y = sin(x) with x from 0 to 2π.

x = 0:0.1:2*pi;

y = sin(x);

plot(x, y);

xlabel('x');

ylabel('y');

title('Plot of y = sin(x)');

disp(' ');

% 11. Plot a bar graph for data x = [1 2 3 4 5 6], y = [10 15 25 30 27 19].

x = [1 2 3 4 5 6];

y = [10 15 25 30 27 19];

bar(x, y);

xlabel('x');
ylabel('y');

title('Bar Graph');

disp(' ');

% 12. 3-D plot with parametric equations x = t^2, y = 4t for -4 < t < 4.

t = -4:0.1:4;

x = t.^2;

y = 4 * t;

plot3(t, x, y);

xlabel('t');

ylabel('x');

zlabel('y');

title('3-D Plot of Parametric Equations');

disp(' ');

% 13. Write a program in MATLAB to find the count of even values in the given n numbers.

n = input('Enter the number of elements: ');

numbers = input('Enter the elements as an array (e.g., [1, 2, 3, 4]): ');

count_even = sum(mod(numbers, 2) == 0);

fprintf("Count of even numbers: %d\n", count_even);

% MATLAB Code Solutions

% Other questions...

% 14. Write a function in MATLAB to calculate the roots of the quadratic equation ax^2 + bx + c = 0.

function roots = quadratic_roots(a, b, c)

% Calculates the roots of ax^2 + bx + c = 0

discriminant = b^2 - 4*a*c;


if discriminant > 0

root1 = (-b + sqrt(discriminant)) / (2 * a);

root2 = (-b - sqrt(discriminant)) / (2 * a);

roots = [root1, root2];

elseif discriminant == 0

root = -b / (2 * a);

roots = [root, root];

else

realPart = -b / (2 * a);

imagPart = sqrt(-discriminant) / (2 * a);

roots = [realPart + 1i * imagPart, realPart - 1i * imagPart];

end

end

% Example usage:

a = 1;

b = -3;

c = 2;

roots_of_quadratic = quadratic_roots(a, b, c);

disp("Roots of the quadratic equation:");

disp(roots_of_quadratic);

disp(' ');

% Continue with other code sections or save each function separately if needed.

You might also like