Object Oriented Problem Exercise Using Python
Object Oriented Problem Exercise Using Python
1. Write a program to print the area of a rectangle by creating a class named 'Area' having two methods. First method named as 'setDim' takes length and breadth of rectangle as parameters and the second method
named as 'getArea' returns the area of the rectangle.Length and breadth of rectangle are entered through keyboard.
In [3]:
class Area:
def setDim(self,l,b):
self.length = l
self.breadth = b
def getArea(self):
t1 = Area()
t1.setDim(a,b)
t1.getArea()
2. Create a class called Complex to represent complex numbers. Include the member method add ( ) to add two complex objects in such a way that the method add ( ) returns the result to the main ( ).
In [2]:
class complex:
self.real = r
self.imaginary = i
def add(self,obj):
temp = complex()
return temp
def showData(self):
c1 = complex()
c2 = complex()
c1.setdata(10,5)
c2.setdata(5,10)
c3 = c1.add(c2)
c3.showData()
3. Write a program to swap the private data members of two classes. Use call by reference feature to do this.
In [3]:
class A:
__list1=[16]
def display1(self):
print(self.__list1)
def getdata(self):
return(self.__list1)
def putdata(self,var):
self.__list1=var
class B:
__list2=[18]
def display2(self):
print(self.__list2)
def getdata(self):
return(self.__list2)
def putdata(self,var):
self.__list2=var
p1=A()
p2=B()
print("Before Swap")
p1.display1()
p2.display2()
temp=p1.getdata()
p1.putdata(p2.getdata())
p2.putdata(temp)
print("After Swap")
p1.display1()
p2.display2()
Before Swap
[16]
[18]
After Swap
[18]
[16]
4. Create two classes DM and DB which store the value of distances. DM stores
distances in metres and centimeters and DB in feet and inches. Write a program
that can read values for the class objects and add
one object of DM with
another object of DB. Use a method to carry out the addition operation. The object that stores the result may be a DM object or a DB object, depending on the units in which the results are
required. The display should
be done in the format of feet and inches or metres and centimeters depending on the object on display
In [4]:
class DM:
def getdata(self,meter,centi):
self.meter=meter
self.centi=centi
class DB:
def getdata(self,feet,inches):
self.feet=feet
self.inches=inches
def add():
if ch==1:
p1=DB()
if c>=12:
p1.feet=c/12
p1.inches=c%12
else:
p1.feet=0
p1.inches=0
if ch==2:
p2=DM()
if c >= 100:
p2.meter = c / 100
p2.centi = c % 100
else:
p2.meter= 0
p2.centi = 0
feet=(float(input("Enter Feet=")))
inches=(float(input("Enter Inches=")))
meter=(float(input("Enter Meter=")))
centi=(float(input("Enter Centimeter=")))
obj1=DM()
obj2=DB()
obj1.getdata(meter,centi)
obj2.getdata(feet,inches)
add()
Enter Feet=5
Enter Inches=6
Enter Meter=5
Enter Centimeter=25
def __init__(self):
self.total_cars = 0
self.total_cash = 0.0
def payingCar(self):
self.total_cars+=1
self.total_cash+=50
def nopayCar(self):
self.total_cars+=1
def display(self):
p1=Tollbooth()
flag=True
while(flag):
print("press 3 to Exit")
if ch==1:
p1.payingCar()
p1.display()
elif ch==2:
p1.nopayCar()
p1.display()
elif ch==3:
flag=False
else:
print("Wrong choice")
press 3 to Exit
press 3 to Exit
press 3 to Exit
press 3 to Exit
press 3 to Exit
6. Define a class named “Student” to store information of a student (roll, name, marksInPhysics, marksInChemistry,marksInMathematics). Write a constructor which will take as input the roll, name and numbers
obtained by several students in different subjects will calculate the total marks obtained by each student and define methods display the list of students in descending order according to the total marks and the
highest marks in each subject and the roll no of the student who secured it
In [4]:
class Student():
def __init__(self,roll,name,physics,chemistry,maths):
self.roll=roll
self.name=name
self.marksInPhysics=physics
self.marksInChemistry=chemistry
self.marksInMaths=maths
self.totalMarks=physics+chemistry+maths
def display(self):
listofstudent=[]
listofstudent.append(Student(101,'Subhasish',80,70,75))
listofstudent.append(Student(102,'Sounak',85,67,82))
listofstudent.append(Student(103,'Basudeb',75,70,75))
listofstudent.append(Student(104,'Jaitra',79,79,65))
listofstudent.append(Student(105,'Suman',82,76,95))
listofstudent.append(Student(106,'Mainak',69,62,64))
listofstudent.append(Student(107,'Satodal',45,77,65))
def myfunc1(self):
return self.totalMarks
def myfunc2(self):
return self.marksInPhysics
listofstudent.sort(reverse=True,key=myfunc1)
for i in listofstudent:
i.display()
listofstudent.sort(reverse=True,key=myfunc2)
listofstudent[0].display()
print("Marks in Physics:",listofstudent[0].marksInPhysics)
def myfunc3(self):
return self.marksInMaths
listofstudent.sort(reverse=True,key=myfunc3)
listofstudent[0].display()
print("Marks in Maths:",listofstudent[0].marksInMaths)
def myfunc4(self):
return self.marksInChemistry
listofstudent.sort(reverse=True,key=myfunc4)
listofstudent[0].display()
print("Marks in Chemistry:",listofstudent[0].marksInChemistry)
Marks in Physics: 85
Marks in Maths: 95
Marks in Chemistry: 79
7. Define a class named “Employee” to store information of an employee (empNo, name, department, basicPay, DA, HRA and grossSalary). Write a constructor which will take as input the empNo, name,
department, basicPay for several employees. The program will calculate the DA, HRA and total for each employee and define a method display the details of the employee having the highest gross salary.
In [6]:
class Employee:
def __init__(self,empNo,name,dept,basicpay):
self.empNo=empNo
self.name=name
self.dept=dept
self.basicpay=basicpay
self.DA=(10/100)*basicpay
self.HRA=(15/100)*basicpay
self.grossSalary=self.DA+self.HRA+basicpay
self.total=self.DA+self.HRA+basicpay+self.grossSalary
def display(self):
print("Employee no.=",self.empNo,"\nName=",self.name,"\nDepartment=",self.dept,"\nBasicpay=",self.basicpay,"\nDA=",self.DA,"\nHRA=",self.HRA,"\nGrossS
listofEmployee=[]
listofEmployee.append(Employee(501,"Subhasish","Sales",12000))
listofEmployee.append(Employee(502,"Sounak","Marketing",25000))
listofEmployee.append(Employee(510,"Satodal","HR",40000))
listofEmployee.append(Employee(503,"Mainak","Accounts",20000))
listofEmployee.append(Employee(504,"Basudeb","Research",22000))
for i in listofEmployee:
i.display()
def myfunc3(self):
return self.grossSalary
listofEmployee.sort(reverse=True,key=myfunc3)
listofEmployee[0].display()
Name= Subhasish
Department= Sales
Basicpay= 12000
DA= 1200.0
HRA= 1800.0
GrossSalary= 15000.0
Name= Sounak
Department= Marketing
Basicpay= 25000
DA= 2500.0
HRA= 3750.0
GrossSalary= 31250.0
Name= Satodal
Department= HR
Basicpay= 40000
DA= 4000.0
HRA= 6000.0
GrossSalary= 50000.0
Name= Mainak
Department= Accounts
Basicpay= 20000
DA= 2000.0
HRA= 3000.0
GrossSalary= 25000.0
Name= Basudeb
Department= Research
Basicpay= 22000
DA= 2200.0
HRA= 3300.0
GrossSalary= 27500.0
Name= Satodal
Department= HR
Basicpay= 40000
DA= 4000.0
HRA= 6000.0
GrossSalary= 50000.0
8. Define a class Account to represent a bank account. Include the following members.
Variable: Name of the depositor, Account number, Account type, Balance amount in the account.
Method: To assign initial
values, To deposit an amount, To withdraw an amount after checking the balance, To display name and balance.
Write a program to test the program for a given number of customers. The program should be able to
search any customer if the account number is provided.
In [2]:
class Account:
def __init__(self,name,accNo,accType,balance):
self.name=name
self.accNo=accNo
self.accType=accType
self.balance=balance
def deposit(self):
self.balance=self.balance+b
print("\nRs",b,"is deposited")
print("Balance is:",self.balance)
def withdraw(self):
if(self.balance<=w or self.balance<=1000):
print("Insufficient Balance")
else:
self.balance=self.balance-w
print("Balance is:",self.balance)
def display(self):
listofAccount=[]
listofAccount.append(Account("Basudeb Basak",2182058,"current",7000))
listofAccount.append(Account("Satodal Karmakar",2182011,"savings",15000))
listofAccount.append(Account("Alekhya Roy",2182001,"savings",9000))
listofAccount.append(Account("Ayush Gupta",2182018,"current",25000))
listofAccount.append(Account("Jaitra Mandal",2182047,"savings",7000))
listofAccount.append(Account("Subhasish Bagchi",2182008,"current",13000))
index=-1
flag=True
found=False
for i in listofAccount:
index+=1
if(c==i.accNo):
found=True
break
if(found==True):
while(flag):
print("\n1.Deposit")
print("2.Withdraw")
print("3.Balance")
print("4.Exit")
if(choice==1):
listofAccount[index].deposit()
elif(choice==2):
listofAccount[index].withdraw()
elif(choice==3):
listofAccount[index].display()
elif(choice==4):
flag=False
else:
print("Wrong choice")
else:
1.Deposit
2.Withdraw
3.Balance
4.Exit
Rs 15000.0 is deposited
1.Deposit
2.Withdraw
3.Balance
4.Exit
Rs 5000.0 is withdrawn
1.Deposit
2.Withdraw
3.Balance
4.Exit
Balance is 23000.0
1.Deposit
2.Withdraw
3.Balance
4.Exit
9. Consider an example of book shop which sells books & video tapes. It’s modeled by Book & Tape classes. These two classes are inherited from the abstract class called Media. The Media class has common data
members such as title & publication. The Book class has data member for storing a no. of pages in a book & Tape class has the playing time in a tape. Each class will have method such as read ( ) & show ( ). Write a
program that models this class hierarchy & processes objects using reference to base class only.
In [2]:
from abc import ABC, abstractmethod
class Media(ABC):
title = "XYZ"
@abstractmethod
def read(self):
pass
def show(self):
pass
class Book(Media):
no_of_pages=100
def read(self):
def show(self):
print("\nThe Book Title is: ",self.title,"\nThe Publication is: ",self.publication,"\nThe Number of pages: ",self.no_of_pages)
class Tape(Media):
playing_time=10
def read(self):
def show(self):
print("\nThe Book Title is: ",self.title,"\nThe Publication is: ",self.publication,"\nThe Number of pages: ",self.playing_time)
b1=Book()
b1.read()
b1.show()
t1=Tape()
t1.read()
t1.show()
10. Create a base class called Shape. Use this class to store two double type values that could be used to compute that could be used to compute the area of figures. Derive three specific classes called Triangle,
Rectangle and Circle from the base Shape. Add to the base class, a constructor to initialize base class data members and another abstract method display_area ( ) to compute and display the area of figures.
Redefine this method in the derived classes to suit their requirements. Using these three classes to design a program that will accept dimensions of a triangle, rectangle and circle interactively and display the area.
Remember that two values given as input will be treated as lengths of two sides in the case of rectangle, as base and height in the case of triangles and radius in the case of a circle.
Area of rectangle: X * Y
Area of
triangle: 1⁄2 * X * Y
Area of circle: π * X * X
In [3]:
from abc import ABC, abstractmethod
class Shape(ABC):
def __init__(self,x=None,y=None):
self.x=x
self.y=y
@abstractmethod
def display_area(self):
pass
class Rectangle(Shape):
def __init__(self,x,y):
Shape.__init__(self,x,y)
def display_area(self):
class Triangle(Shape):
def __init__(self,x,y):
Shape.__init__(self,x,y)
def display_area(self):
class Circle(Shape):
def __init__(self,x):
Shape.__init__(self,x)
def display_area(self):
r=Rectangle(7,8)
r.display_area()
t=Triangle(6,5)
t.display_area()
c=Circle(8)
c.display_area()
11. Write a program to create a class called MyStack that includes method to perform all operations on a stack as well as raises an exception whenever overflow/underflow error occurs.
In [11]:
class MyStack:
def __init__(self):
self.items = []
def is_empty(self):
return self.items == []
def is_full(self):
if len(self.items)==size:
return True
else:
return False
def display(self):
print(self.items)
self.items.append(data)
def pop(self):
return self.items.pop()
s = MyStack()
while True:
print('push <value>')
print('pop')
print('display')
print('quit')
operation = do[0].strip().lower()
if operation == 'push':
if s.is_full():
s.push(int(do[1]))
if s.is_empty():
else:
s.display()
break
push <value>
pop
display
quit
push <value>
pop
display
quit
[15]
push <value>
pop
display
quit
Popped value: 15
push <value>
pop
display
quit
[]
push <value>
pop
display
quit
12. Write a program to create a class called MyQueue that will trigger an exception when too many items are put in the queue and if the item are not present in the queue.
In [1]:
class MyQueue:
def __init__(self):
self.items = []
def is_empty(self):
return self.items == []
def is_full(self):
if len(self.items)==size:
return True
else:
return False
def check(self,val):
if self.items.count(val)>=1:
return True
else:
return False
def display(self):
print(self.items)
self.items.append(data)
def dequeue(self):
return self.items.pop(0)
q = MyQueue()
while True:
print('enqueue <value>')
print('dequeue')
print('display')
print('check_item')
print('quit')
operation = do[0].strip().lower()
if operation == 'enqueue':
if q.is_full():
else:
q.enqueue(int(do[1]))
if q.is_empty():
else:
q.display()
elif operation=='check_item':
if q.is_empty():
else:
if q.check(s):
print("Item is present")
else:
break
enqueue <value>
dequeue
display
check_item
quit
enqueue <value>
dequeue
display
check_item
quit
enqueue <value>
dequeue
display
check_item
quit
enqueue <value>
dequeue
display
check_item
quit
enqueue <value>
dequeue
display
check_item
quit
enqueue <value>
dequeue
display
check_item
quit
enqueue <value>
dequeue
display
check_item
quit
Item is present
enqueue <value>
dequeue
display
check_item
quit
Dequeued value: 15
enqueue <value>
dequeue
display
check_item
quit
Dequeued value: 20
enqueue <value>
dequeue
display
check_item
quit
Dequeued value: 25
enqueue <value>
dequeue
display
check_item
quit
Dequeued value: 30
enqueue <value>
dequeue
display
check_item
quit
Dequeued value: 35
enqueue <value>
dequeue
display
check_item
quit
[]
enqueue <value>
dequeue
display
check_item
quit