0% found this document useful (0 votes)
73 views1 page

Object Oriented Problem Exercise Using Python

1. Create a class called Area with methods to set the dimensions of a rectangle and calculate its area. The program takes user input for length and breadth and prints the area. 2. Create a Complex class to represent complex numbers. Include an add() method to add two complex objects and return the result. 3. Create classes A and B to store private data. Write a program that swaps the private data of two objects using call by reference.

Uploaded by

Subhasish Bagchi
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)
73 views1 page

Object Oriented Problem Exercise Using Python

1. Create a class called Area with methods to set the dimensions of a rectangle and calculate its area. The program takes user input for length and breadth and prints the area. 2. Create a Complex class to represent complex numbers. Include an add() method to add two complex objects and return the result. 3. Create classes A and B to store private data. Write a program that swaps the private data of two objects using call by reference.

Uploaded by

Subhasish Bagchi
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/ 1

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):

self.area = self.length * self.breadth

print("The area of the rectangle is: ",self.area)

a = int(input('Enter the length of a rectangle: '))

b = int(input('Enter the breadth of a rectangle: '))

t1 = Area()

t1.setDim(a,b)

t1.getArea()

Enter the length of a rectangle: 10

Enter the breadth of a rectangle: 12

The area of the rectangle is: 120

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:

def setdata(self, r, i):

self.real = r

self.imaginary = i

def add(self,obj):

temp = complex()

temp.real = self.real + obj.real

temp.imaginary = self.imaginary + obj.imaginary

return temp

def showData(self):

print("The complex number is: ",self.real,"+",self.imaginary,"i")

c1 = complex()

c2 = complex()

c1.setdata(10,5)

c2.setdata(5,10)

c3 = c1.add(c2)

c3.showData()

The complex number is: 15 + 15 i

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():

print("press 1 for feet-inches")

print("press 2 for meter-centi")

ch=int(input("Enter your choice"))

if ch==1:

p1=DB()

c = int(obj1.meter * 39.37 + obj1.centi * .3937008 + obj2.feet * 12 + obj2.inches);

if c>=12:

p1.feet=c/12

p1.inches=c%12

else:

p1.feet=0

p1.inches=0

print("Feet= ",p1.feet,end=" ")

print("Inches= ",p1.inches,end=" ")

if ch==2:

p2=DM()

c = int(obj1.meter * 100 + obj1.centi + obj2.feet * 30.48 + obj2.inches * 2.54);

if c >= 100:

p2.meter = c / 100

p2.centi = c % 100

else:

p2.meter= 0

p2.centi = 0

print("Meter= ", p2.meter, end=" ")

print("Centimeter= ", p2.centi, end=" ")

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

press 1 for feet-inches

press 2 for meter-centi

Enter your choice1

Feet= 22.666666666666668 Inches= 8


5. Imagine a tollbooth at a bridge. Cars passing by the booth are expected
to pay Rs. 50 toll. Mostly they do, but sometimes a car goes by without paying. The tollbooth keeps track of the number of cars that have
gone by, and of the total amount of money collected. Model this tollbooth with a class
called tollbooth. The two data items are type unsigned int to hold the total
number of cars, and a type double to hold the total
amount of money collected.
A constructor initializes both of these to 0. A method called payingCar() increments the car total and adds Rs. 50 to the cash total. Another method, called nopayCar(), increments the car
total but adds nothing to the cash total. Finally, method called display() displays the two totals.
In [2]:
class Tollbooth:

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):

print("Total cars= ",self.total_cars,"Total Cash= ",self.total_cash)

p1=Tollbooth()

flag=True

while(flag):

print("press 1 for Paid")

print("press 2 for NotPaid")

print("press 3 to Exit")

ch=int(input("Enter the choice:"))

if ch==1:

p1.payingCar()

p1.display()

elif ch==2:

p1.nopayCar()

p1.display()

elif ch==3:

flag=False

else:

print("Wrong choice")

press 1 for Paid

press 2 for NotPaid

press 3 to Exit

Enter the choice:2

Total cars= 1 Total Cash= 0.0

press 1 for Paid

press 2 for NotPaid

press 3 to Exit

Enter the choice:1

Total cars= 2 Total Cash= 50.0

press 1 for Paid

press 2 for NotPaid

press 3 to Exit

Enter the choice:1

Total cars= 3 Total Cash= 100.0

press 1 for Paid

press 2 for NotPaid

press 3 to Exit

Enter the choice:2

Total cars= 4 Total Cash= 100.0

press 1 for Paid

press 2 for NotPaid

press 3 to Exit

Enter the choice:3

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):

print("Name:",self.name," Roll:",self.roll," Total Marks:",self.totalMarks)

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)

print("Student with highest marks in physics:")

listofstudent[0].display()

print("Marks in Physics:",listofstudent[0].marksInPhysics)

def myfunc3(self):

return self.marksInMaths

listofstudent.sort(reverse=True,key=myfunc3)

print("Student with highest marks in maths:")

listofstudent[0].display()

print("Marks in Maths:",listofstudent[0].marksInMaths)

def myfunc4(self):

return self.marksInChemistry

listofstudent.sort(reverse=True,key=myfunc4)

print("Student with highest marks in Chemistry:")

listofstudent[0].display()

print("Marks in Chemistry:",listofstudent[0].marksInChemistry)

Name: Suman Roll: 105 Total Marks: 253

Name: Sounak Roll: 102 Total Marks: 234

Name: Subhasish Roll: 101 Total Marks: 225

Name: Jaitra Roll: 104 Total Marks: 223

Name: Basudeb Roll: 103 Total Marks: 220

Name: Mainak Roll: 106 Total Marks: 195

Name: Satodal Roll: 107 Total Marks: 187

Student with highest marks in physics:

Name: Sounak Roll: 102 Total Marks: 234

Marks in Physics: 85

Student with highest marks in maths:

Name: Suman Roll: 105 Total Marks: 253

Marks in Maths: 95

Student with highest marks in Chemistry:

Name: Jaitra Roll: 104 Total Marks: 223

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)

print("Employee with highest grossSalary:")

listofEmployee[0].display()

Employee no.= 501

Name= Subhasish

Department= Sales

Basicpay= 12000

DA= 1200.0

HRA= 1800.0

GrossSalary= 15000.0

Employee no.= 502

Name= Sounak

Department= Marketing

Basicpay= 25000

DA= 2500.0

HRA= 3750.0

GrossSalary= 31250.0

Employee no.= 510

Name= Satodal

Department= HR

Basicpay= 40000

DA= 4000.0

HRA= 6000.0

GrossSalary= 50000.0

Employee no.= 503

Name= Mainak

Department= Accounts

Basicpay= 20000

DA= 2000.0

HRA= 3000.0

GrossSalary= 25000.0

Employee no.= 504

Name= Basudeb

Department= Research

Basicpay= 22000

DA= 2200.0

HRA= 3300.0

GrossSalary= 27500.0

Employee with highest grossSalary:

Employee no.= 510

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):

b=float(input("Enter the amount: "))

self.balance=self.balance+b

print("\nRs",b,"is deposited")

print("Balance is:",self.balance)

def withdraw(self):

w=float(input("Enter the amount to withdraw:"))

if(self.balance<=w or self.balance<=1000):

print("Insufficient Balance")

else:

self.balance=self.balance-w

print("\nRs", w, "is withdrawn")

print("Balance is:",self.balance)

def display(self):

print("\nName:",self.name,"\nAccount Number:",self.accNo,"\nAccount type:",self.accType,"\nBalance is",self.balance)

listofAccount=[]

listofAccount.append(Account("Basudeb Basak",2182058,"current",7000))

listofAccount.append(Account("Mainak Mitra", 2182048, "current", 15000))

listofAccount.append(Account("Sounak Pal", 2182007, "savings", 5000))

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))

c=int(input("Enter your account number: "))

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")

choice=int(input("Enter your choice:"))

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:

print("Account not found!!")

Enter your account number: 2182008

1.Deposit

2.Withdraw
3.Balance

4.Exit

Enter your choice:1

Enter the amount: 15000

Rs 15000.0 is deposited

Balance is: 28000.0

1.Deposit

2.Withdraw
3.Balance

4.Exit

Enter your choice:2

Enter the amount to withdraw:5000

Rs 5000.0 is withdrawn

Balance is: 23000.0

1.Deposit

2.Withdraw
3.Balance

4.Exit

Enter your choice:3

Name: Subhasish Bagchi

Account Number: 2182008

Account type: current

Balance is 23000.0

1.Deposit

2.Withdraw
3.Balance

4.Exit

Enter your choice:4

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"

publication = "VM Publication"

@abstractmethod

def read(self):

pass

def show(self):

pass

class Book(Media):

no_of_pages=100

def read(self):

self.title=input("Enter the Book Title: ")

self.publication=input("Enter the Publication name: ")

self.no_of_pages=int(input("Enter the no of pages: "))

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):

self.title = input("Enter the Tape Title: ")

self.publication = input("Enter the Publication name: ")

self.playing_time=int(input("Enter the playing time: "))

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()

Enter the Book Title: XYZ

Enter the Publication name: VM publication

Enter the no of pages: 100

The Book Title is: XYZ

The Publication is: VM publication

The Number of pages: 100

Enter the Tape Title: ABC

Enter the Publication name: MV publication

Enter the playing time: 10

The Book Title is: ABC

The Publication is: MV publication

The Number of pages: 10

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):

print("The Area of Rectangle is= ",self.x*self.y)

class Triangle(Shape):

def __init__(self,x,y):

Shape.__init__(self,x,y)

def display_area(self):

print("The Area of Triangle is= ",(1/2)*self.x*self.y)

class Circle(Shape):

def __init__(self,x):

Shape.__init__(self,x)

def display_area(self):

print("The Area of Circle is= ",(3.14)*self.x*self.x)


r=Rectangle(7,8)

r.display_area()

t=Triangle(6,5)

t.display_area()

c=Circle(8)

c.display_area()

The Area of Rectangle is= 56

The Area of Triangle is= 15.0

The Area of Circle is= 200.96

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)

def push(self, data):

self.items.append(data)

def pop(self):

return self.items.pop()

size=int(input("Enter the size of stack: "))

s = MyStack()

while True:

print('push <value>')

print('pop')

print('display')

print('quit')

do = input('What would you like to do? ').split()

operation = do[0].strip().lower()

if operation == 'push':

if s.is_full():

raise Exception("OVERFLOW OCCURS")


else:

s.push(int(do[1]))

elif operation == 'pop':

if s.is_empty():

raise Exception("UNDERFLOW OCCURS")

else:

print('Popped value: ', s.pop())

elif operation == 'display':

s.display()

elif operation == 'quit':

break

Enter the size of stack: 2

push <value>

pop

display

quit

What would you like to do? push 15

push <value>

pop

display

quit

What would you like to do? display

[15]

push <value>

pop

display

quit

What would you like to do? pop

Popped value: 15

push <value>

pop

display

quit

What would you like to do? display

[]

push <value>

pop

display

quit

What would you like to do? 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)

def enqueue(self, data):

self.items.append(data)

def dequeue(self):

return self.items.pop(0)

size=int(input("Enter the size of queue: "))

q = MyQueue()

while True:

print('enqueue <value>')

print('dequeue')

print('display')

print('check_item')

print('quit')

do = input('What would you like to do? ').split()

operation = do[0].strip().lower()

if operation == 'enqueue':

if q.is_full():

raise Exception("Queue is full")

else:

q.enqueue(int(do[1]))

elif operation == 'dequeue':

if q.is_empty():

raise Exception("Queue is empty")

else:

print('Dequeued value: ', q.dequeue())

elif operation == 'display':

q.display()

elif operation=='check_item':

if q.is_empty():

raise Exception("Queue is empty")

else:

s=int(input("Enter the item you want to check: "))

if q.check(s):

print("Item is present")

else:

print("Item is not present")

elif operation == 'quit':

break

Enter the size of queue: 5

enqueue <value>

dequeue

display

check_item
quit

What would you like to do? enqueue 15

enqueue <value>

dequeue

display

check_item
quit

What would you like to do? enqueue 20

enqueue <value>

dequeue

display

check_item
quit

What would you like to do? enqueue 25

enqueue <value>

dequeue

display

check_item
quit

What would you like to do? enqueue 30

enqueue <value>

dequeue

display

check_item
quit

What would you like to do? enqueue 35

enqueue <value>

dequeue

display

check_item
quit

What would you like to do? display

[15, 20, 25, 30, 35]

enqueue <value>

dequeue

display

check_item
quit

What would you like to do? check_item

Enter the item you want to check: 25

Item is present

enqueue <value>

dequeue

display

check_item
quit

What would you like to do? dequeue

Dequeued value: 15

enqueue <value>

dequeue

display

check_item
quit

What would you like to do? dequeue

Dequeued value: 20

enqueue <value>

dequeue

display

check_item
quit

What would you like to do? dequeue

Dequeued value: 25

enqueue <value>

dequeue

display

check_item
quit

What would you like to do? dequeue

Dequeued value: 30

enqueue <value>

dequeue

display

check_item
quit

What would you like to do? dequeue

Dequeued value: 35

enqueue <value>

dequeue

display

check_item
quit

What would you like to do? display

[]

enqueue <value>

dequeue

display

check_item
quit

What would you like to do? quit

You might also like