Python Worksheet 3.2
Python Worksheet 3.2
Python Worksheet 3.2
WORKSHEET – 3.2
PROGRAM CODE –
class Student:
def __init__(self, student_id, student_name):
self.student_id = student_id
self.student_name = student_name
print(student.__dict__)
del student.student_name
print(student.__dict__)
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
student1.remove_name()
student1.display_attributes()
OUTPUT –
b) Write a Python class to find a pair of elements (indices of the two numbers)
from a given array whose sum equals a specific target number.
PROGRAM CODE –
class TwoSum:
def init (self, nums, target):
self.nums = nums
self.target = target
def find_indices(self):
index_map = {}
for i, num in enumerate(self.nums):
complement = self.target - num
if complement in index_map:
return [index_map[complement], i]
index_map[num] = i
return None
nums = [2, 7, 11, 15]
target = 9
two_sum = TwoSum(nums, target)
indices = two_sum.find_indices()
print(indices)
OUTPUT –
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
PROGRAM CODE –
class Rectangle:
def init (self, length, width):
self.length = length
self.width = width
def area(self):
return self.length * self.width
rectangle = Rectangle(5, 7)
area = rectangle.area()
print("Area of the rectangle is:", area)
OUTPUT –
PROGRAM CODE –
class Circle:
def init (self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius ** 2
def perimeter(self):
return 2 * 3.14 * self.radius
circle = Circle(5)
area = circle.area()
perimeter = circle.perimeter()
print("Area of the circle is:", area)
print("Perimeter of the circle is:", perimeter)
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
OUTPUT –
PROGRAM CODE –
class
Student:
pass
class
Marks:
pass
student1 =
Student()student2
= Student() marks1
= Marks() marks2
= Marks()
print(isinstance(student1,
Student))
print(isinstance(student2,
Student))
print(isinstance(marks1,
Marks))
print(isinstance(marks2,
Marks))
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
print(issubclass(Student, object))
print(issubclass(Marks, object))
OUTPUT –