0% found this document useful (0 votes)
56 views6 pages

C++ Pracatical 7-11

The document discusses several Python programming concepts including: 1) Defining recursive and non-recursive functions to calculate the greatest common divisor (GCD) of two numbers. 2) Creating a Matrix class with methods to perform matrix addition, multiplication, and transposition operations. The class includes exception handling for incompatible matrix operations. 3) Defining classes for Person, Student, and Employee with inheritance and polymorphism.

Uploaded by

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

C++ Pracatical 7-11

The document discusses several Python programming concepts including: 1) Defining recursive and non-recursive functions to calculate the greatest common divisor (GCD) of two numbers. 2) Creating a Matrix class with methods to perform matrix addition, multiplication, and transposition operations. The class includes exception handling for incompatible matrix operations. 3) Defining classes for Person, Student, and Employee with inheritance and polymorphism.

Uploaded by

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

7.

) Write a program to calculate GCD of two numbers (i) with recursion (ii) without
recursion.

def gcd_recursive(a, b):


if b == 0:
return a
else:
return gcd_recursive(b, a % b)

# Example usage
num1 = 36
num2 = 48
result = gcd_recursive(num1, num2)
print(f"The GCD of {num1} and {num2} is: {result}")

8.) Create a Matrix class. Write a menu-driven program to perform following Matrix
operations (exceptions should be thrown by the functions if matrices passed to them
are
incompatible and handled by the main() function):
a. Sum
b. Product
c. Transpose

class Matrix:
def __init__(self, rows, cols):
self.rows = rows
self.cols = cols
self.data = [[0] * cols for _ in range(rows)]

def set_value(self, row, col, value):


self.data[row][col] = value

def get_value(self, row, col):


return self.data[row][col]

def add(self, other):


if self.rows != other.rows or self.cols != other.cols:
raise ValueError("Matrices are incompatible for addition.")

result = Matrix(self.rows, self.cols)


for i in range(self.rows):
for j in range(self.cols):
result.set_value(i, j, self.get_value(i, j) + other.get_value(i,
j))

return result

def multiply(self, other):


if self.cols != other.rows:
raise ValueError("Matrices are incompatible for multiplication.")

result = Matrix(self.rows, other.cols)


for i in range(self.rows):
for j in range(other.cols):
value = 0
for k in range(self.cols):
value += self.get_value(i, k) * other.get_value(k, j)
result.set_value(i, j, value)

return result

def transpose(self):
result = Matrix(self.cols, self.rows)
for i in range(self.rows):
for j in range(self.cols):
result.set_value(j, i, self.get_value(i, j))

return result

def create_matrix():
rows = int(input("Enter the number of rows: "))
cols = int(input("Enter the number of columns: "))
matrix = Matrix(rows, cols)

for i in range(rows):
for j in range(cols):
value = float(input(f"Enter value for matrix[{i}][{j}]: "))
matrix.set_value(i, j, value)

return matrix

def print_matrix(matrix):
for i in range(matrix.rows):
for j in range(matrix.cols):
print(matrix.get_value(i, j), end="\t")
print()

def menu():
print("Matrix Operations:")
print("a. Sum")
print("b. Product")
print("c. Transpose")
print("x. Exit")

def main():
while True:
menu()
choice = input("Enter your choice: ")

if choice == "a":
matrix1 = create_matrix()
matrix2 = create_matrix()

try:
result = matrix1.add(matrix2)
print("Result:")
print_matrix(result)
except ValueError as e:
print("Error:", e)

elif choice == "b":


matrix1 = create_matrix()
matrix2 = create_matrix()

try:
result = matrix1.multiply(matrix2)
print("Result:")
print_matrix(result)
except ValueError as e:
print("Error:", e)

elif choice == "c":


matrix = create_matrix()
result = matrix.transpose()
print("Result:")
print_matrix(result)

elif choice == "x":


break

else:
print("Invalid choice. Please try again.")

9.) Define a class Person having name as a data member. Inherit two classes Student
and
Employee from Person. Student has additional attributes as course, marks and year
and
Employee has department and salary. Write display() method in all the three classes
to
display the corresponding attributes. Provide the necessary methods to show runtime
polymorphism

class Person:
def __init__(self, name):
self.name = name

def display(self):
print("Name:", self.name)

class Student(Person):
def __init__(self, name, course, marks, year):
super().__init__(name)
self.course = course
self.marks = marks
self.year = year

def display(self):
super().display()
print("Course:", self.course)
print("Marks:", self.marks)
print("Year:", self.year)

class Employee(Person):
def __init__(self, name, department, salary):
super().__init__(name)
self.department = department
self.salary = salary
def display(self):
super().display()
print("Department:", self.department)
print("Salary:", self.salary)

# Runtime Polymorphism Example


person = Person("John")
student = Student("Alice", "Computer Science", 90, 2022)
employee = Employee("Bob", "IT", 50000)

person.display()
print()
student.display()
print()
employee.display()

10.) Create a Triangle class. Add exception handling statements to ensure the
following
conditions: all sides are greater than 0 and sum of any two sides are greater than
the
third side. The class should also have overloaded functions for calculating the
area of
a right angled triangle as well as using Heron's formula to calculate the area of
any type
of triangle

import math

class Triangle:
def __init__(self, side1, side2, side3):
self.side1 = side1
self.side2 = side2
self.side3 = side3

if not self.is_valid():
raise ValueError("Invalid triangle sides")

def is_valid(self):
if self.side1 <= 0 or self.side2 <= 0 or self.side3 <= 0:
return False

if (self.side1 + self.side2) <= self.side3:


return False

if (self.side2 + self.side3) <= self.side1:


return False

if (self.side1 + self.side3) <= self.side2:


return False

return True

def calculate_area(self):
if self.is_right_angle_triangle():
return self.calculate_right_angle_area()
else:
return self.calculate_heron_area()

def is_right_angle_triangle(self):
sides = [self.side1, self.side2, self.side3]
sides.sort()
return math.isclose(sides[0] ** 2 + sides[1] ** 2, sides[2] ** 2)

def calculate_right_angle_area(self):
sides = [self.side1, self.side2, self.side3]
sides.sort()
return 0.5 * sides[0] * sides[1]

def calculate_heron_area(self):
s = (self.side1 + self.side2 + self.side3) / 2
area = math.sqrt(s * (s - self.side1) * (s - self.side2) * (s -
self.side3))
return area

11.)Create a class Student containing fields for Roll No., Name, Class, Year and
Total
Marks. Write a program to store 5 objects of Student class in a file. Retrieve
these
records from the file and display them.

import pickle

class Student:
def __init__(self, roll_no, name, student_class, year, total_marks):
self.roll_no = roll_no
self.name = name
self.student_class = student_class
self.year = year
self.total_marks = total_marks

def display(self):
print(f"Roll No: {self.roll_no}")
print(f"Name: {self.name}")
print(f"Class: {self.student_class}")
print(f"Year: {self.year}")
print(f"Total Marks: {self.total_marks}")

# Create 5 Student objects


students = [
Student(1, "John Doe", "Class A", 2022, 95),
Student(2, "Jane Smith", "Class B", 2023, 88),
Student(3, "Michael Johnson", "Class A", 2022, 92),
Student(4, "Emily Davis", "Class C", 2023, 85),
Student(5, "David Wilson", "Class B", 2022, 90)
]

# Store the objects in a file


file_name = "students_data.pickle"
with open(file_name, "wb") as file:
pickle.dump(students, file)

# Retrieve the objects from the file


with open(file_name, "rb") as file:
retrieved_students = pickle.load(file)

# Display the retrieved objects


for student in retrieved_students:
student.display()
print()

You might also like