[go: up one dir, main page]

0% found this document useful (0 votes)
10 views16 pages

Oops Assignment

The document contains multiple Python programming tasks demonstrating concepts such as multiple inheritance, polymorphism, abstraction, and class properties. It includes examples of creating classes for employees, vehicles, cricket scores, a card game, and triangles, along with methods to manipulate and evaluate their properties. Each task is followed by a solution that illustrates the implementation of the respective concept.

Uploaded by

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

Oops Assignment

The document contains multiple Python programming tasks demonstrating concepts such as multiple inheritance, polymorphism, abstraction, and class properties. It includes examples of creating classes for employees, vehicles, cricket scores, a card game, and triangles, along with methods to manipulate and evaluate their properties. Each task is followed by a solution that illustrates the implementation of the respective concept.

Uploaded by

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

Q1. Write a Python program to demonstrate multiple inheritance.

1. Employee class has 3 data members EmployeeID, Gender (String), Salary and Performance Rating(Out of
5) of type int. It has a get() function to get these details from the user.

2. Joining Detail class has a data member DateOfJoining of type Date and a function getDoJ to get the Date
of joining of employees.

3. Information Class uses the marks from Employee class and the DateOfJoining date from the
JoiningDetail class to calculate the top 3 Employees based on their Ratings and then Display, using
readData, all the details on these employees in Ascending order of their Date Of Joining.

Solution:

class Employee:

def get(self):

self.EmployeeID = int(input("Enter Employee ID: "))

self.Gender = input("Enter Gender: ")

self.Salary = float(input("Enter Salary: "))

self.PerformanceRating = int(input("Enter Performance Rating (Out of 5): "))

class JoiningDetail:

def getDoJ(self):

self.DateOfJoining = input("Enter Date of Joining (YYYY-MM-DD): ")

class Information(Employee, JoiningDetail):

def readData(self):

employees = []

for _ in range(3):

emp = Information()

emp.get()

emp.getDoJ()

employees.append(emp)

top_3_employees = sorted(employees, key=lambda x: x.PerformanceRating, reverse=True)[:3]

top_3_employees = sorted(top_3_employees, key=lambda x: x.DateOfJoining)

for emp in top_3_employees:

print(f"Employee ID: {emp.EmployeeID}, Gender: {emp.Gender}, Salary: {emp.Salary}, Performance


Rating: {emp.PerformanceRating}, Date of Joining: {emp.DateOfJoining}")
# Example usage

info = Information()

info.readData()

Q.2 Write a Python program to demonstrate Polymorphism.

1. Class Vehicle with a parameterized function Fare, that takes input value as fare and returns it to
calling Objects.

2. Create five separate variables Bus, Car, Train, Truck and Ship that call the Fare function.

3. Use a third variable TotalFare to store the sum of fare for each Vehicle Type.

4. Print the TotalFare.

Solution:

class Vehicle:

def Fare(self, fare):

return fare

# Creating instances of the Vehicle class

bus = Vehicle()

car = Vehicle()

train = Vehicle()

truck = Vehicle()

ship = Vehicle()

# Calling the Fare function for each vehicle and storing the fare

bus_fare = bus.Fare(50)

car_fare = car.Fare(100)

train_fare = train.Fare(150)

truck_fare = truck.Fare(200)

ship_fare = ship.Fare(250)
# Calculating the total fare

total_fare = bus_fare + car_fare + train_fare + truck_fare + ship_fare

# Printing the total fare

print(total_fare)

Q3. Consider an ongoing test cricket series. Following are the names of the players and their

scores in the test1 and 2.

Test Match 1 :

Dhoni : 56 , Balaji : 94

Test Match 2 :

Balaji : 80 , Dravid : 105

Calculate the highest number of runs scored by an individual cricketer in both of the matches.

Create a python function Max_Score (M) that reads a dictionary M that recognizes the player with
the highest total score. This function will return ( Top player , Total Score ) . You can consider the Top
player as String who is the highest scorer and Top score as Integer .

Input : Max_Score({‘test1’:{‘Dhoni’:56, ‘Balaji : 85}, ‘test2’:{‘Dhoni’ 87, ‘Balaji’’:200}})

Output : (‘Balaji ‘ , 200)

Solution:

M = {'test1': {'Dhoni': 56, 'Balaji': 85}, 'test2': {'Dhoni': 87, 'Balaji': 200}}

def Max_Score(d):

total = {}

for key in d.keys():

for n in d[key].keys():

if n in total.keys(): total[n] = total[n] + d[key][n]

else:

total[n] = d[key][n]

print("Total Runs Scored\n")

Q4. Create a simple Card game in which there are 8 cards which are randomly chosen from a

deck. The first card is shown face up. The game asks the player to predict whether the next card

in the selection will have a higher or lower value than the currently showing card.
For example, say the card that’s shown is a 3. The player chooses “higher,” and the next card is

shown. If that card has a higher value, the player is correct. In this example, if the player had

chosen “lower,” they would have been incorrect. If the player guesses correctly, they get 20

points. If they choose incorrectly, they lose 15 points. If the next card to be turned over has the

same value as the previous card, the player is incorrect.

Solution:

class Deck:

def __init__(self):

self.deck = dict()

self.suit = ("Clubs", "Diamonds", "Hearts", "Spades")

self.card = ("Ace", 2, 3, 4, 5, 6, 7, 8, 9, 10, "Jack", "Queen", "King")

for suit in self.suit:

self.deck[suit] = list(self.card)

@property

def is_empty(self) -> bool:

result = True

for suit in self.suit:

if self.deck[suit]:

result = False

break

return result

def has_a_card(self, suit: str, card: str | int) -> bool:

result = False

if card in self.deck[suit]:

result = True

return result

def remove_a_card(self, suit: str, card: str | int) -> bool:

assert isinstance(suit, str)

assert isinstance(card, str) or isinstance(card, int)

try:

if not self.is_empty and self.has_a_card(suit, card):


self.deck[suit].remove(card)

return True

else:

print(f'===WARNING!!!===: Randomly chosen "{card} of {suit}" was removed

return False

except AssertionError as e:

print(e

def clearify(self) -> None:

"""

Take all cards away from deck :

return: None

"""

if not self.is_empty:

for suit in self.deck:

self.deck[suit] = []

def __repr__(self):

return f'Deck:\n{self.deck}'

class Card:

def __init__(self, suit: str, card: str | int) -> None:

"""

:type card: str or int

"""

assert isinstance(suit, str)

assert (isinstance(card, str) or isinstance(card, int))

assert suit in ("Clubs", "Diamonds", "Hearts", "Spades")

assert card in ("Ace", 2, 3, 4, 5, 6, 7, 8, 9, 10, "Jack", "Queen", "King")

try:

self.suit = suit

if type(card) == str:

if card == "Jack":

self.card = ("Jack", 11)


elif card == "Queen":

self.card = ("Queen", 12)

elif card == "King":

self.card = ("King", 13)

elif card == "Ace":

self.card = ("Ace", 14)

elif type(card) == int:

self.card = (card, card)

except AssertionError as e:

print(e)

def __lt__(self, other):

if self.card[1] < other.card[1]:

return True

else:

return False

def __gt__(self, other):

if self.card[1] > other.card[1]:

return True

else:

return False

def __eq__(self, other):

if self.card[1] == other.card[1]:

return True

else:

return False

def __repr__(self):

return f'"{self.card[0]} of {self.suit}"'

def take_cards(num_of_cards: int) -> list:

deck = Deck()

cards_taken: list[Card] = []

i=0
while i < num_of_cards:

suit = rand_choice(deck.suit)

card = rand_choice(deck.deck[suit])

# if randomly chosen card is in the deck, remove it from the deck

# else repeat randomly choosing a card (at the same iteration),

# while index "i" is not incremented

if deck.remove_a_card(suit, card):

card = Card(suit, card)

cards_taken.append(card)

i += 1

return cards_taken

def play_game(cards_taken) -> None:

score = 0

print(f'ONLY FOR DEBUGGING!!! Do not show all {len(cards_taken)} card(s)to a player!


print(f'ONLY FOR DEBUGGING!!! Cards randomly taken from the deck:\n{cards_taken}\n')
curr_card = cards_taken[0]

cards_taken.pop(0)

i=1

while cards_taken:

# print(f'ONLY FOR DEBUGGING!!! Remaining cards randomly taken from the deck:\n{c
print(f'Card taken from remaining {len(cards_taken) + 1} chosen card(s): {curr_ca

while True:

try:

print(f'{i}. Guess, if the next card would be higher or lower of the curr
guess = int(input(f'(For "higher" enter 1, for "lower" enter 0): '))

assert guess in (0, 1)

break

except ValueError:

print('\nVALUE WARNING: Incorrect input!\n')

print(f'Card taken from remaining {len(cards_taken) + 1} chosen card(s):


except AssertionError:

print('\nASSERT WARNING: Incorrect input!\n')

print(f'Card taken from remaining {len(cards_taken) + 1} chosen card(s):


next_card = cards_taken[0]

cards_taken.pop(0)

if guess == 1:

if curr_card < next_card:

score += 20

print(f"\nCORRECT: You get 20 points. Current score:{score}\n")

else: score -= 15

print(f"\nINCORRECT: You lose 15 points.Current score:{score}\n")


elif guess == 0:

if curr_card > next_card:

score += 20

print(f"\nCORRECT: You get 20 points. Current score: {score}\n")

else:

score -= 15

print(f"\nINCORRECT: You lose 15 points. Current score:{score}\n")


curr_card = next_card

i += 1

print(f'Card taken from remaining {len(cards_taken) + 1} chosen card(s): {curr_card}'

print(f"Total score: {score}")

Q5. Create an empty dictionary called Car_0 . Then fill the dictionary with Keys : color , speed

, X_position and Y_position.

car_0 = {'x_position': 10, 'y_position': 72, 'speed': 'medium'} .

a) If the speed is slow the coordinates of the X_pos get incremented by 2.

b) If the speed is Medium the coordinates of the X_pos gets incremented by 9

c) Now if the speed is Fast the coordinates of the X_pos gets incremented by 22.

Print the modified dictionary.

Solution:

Car_0 = {}

Car_0['x_position'] = 10

Car_0['y_position'] = 72

Car_0['speed'] = 'medium'
Car_0['color'] = 'red'

if Car_0['speed'] == 'slow':

Car_0['x_position'] += 2

elif Car_0['speed'] == 'medium':

Car_0['x_position'] += 9

elif Car_0['speed'] == 'fast':

Car_0['x_position'] += 22

print(Car_0)

{'x_position': 19, 'y_position': 72, 'speed': 'medium', 'color': 'red'}

Q6. Show a basic implementation of abstraction in python using the abstract classes.

1. Create an abstract class in python.

2. Implement abstraction with the other classes and base class as abstract class.

Solution:

import abc

Class parent:

def geeks(self):

pass

class child(parent):

def geeks(self):

print("child class")

# Driver code

print( issubclass(child, parent))

print( isinstance(child(), parent))

Output :

True

True

Q7. Create a program in python to demonstrate Polymorphism.

1. Make use of private and protected members using python name mangling techniques
Solution:

class Student:
def __init__(self, name):
self.__name = name

def displayName(self):
print(self.__name)

s1 = Student("Sumant")

s1.displayName()

print(s1.__name)

Output: Sumant

Q8. Given a list of 50 natural numbers from 1-50. Create a function that will take every element

from the list and return the square of each element. Use the python map and filter methods to

implement the function on the given list.

Solution:

l = []

for i in range(1, 51):

l.append(i * i)

print("List with square of integers from 1 to 50:")

print(l)

Output :

List with square of integers from 1 to 50:

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400, 441, 484, 529, 576,
625, 676, 729, 784, 841, 900, 961, 1024, 1089, 1156, 1225, 1296, 1369, 1444, 1521, 1600, 1681, 1764,
1849, 1936, 2025, 2116, 2209, 2304, 2401, 2500]

Q9. Create a class, Triangle. Its init() method should take self, angle1, angle2, and angle3 as

arguments.
Solution:

class Triangle(object):

def __init__(self,angle1,angle2,angle3):
self.angle1=angle1

self.angle2=angle2

self.angle3=angle3

number_of_sides=3

def check_angles(self):

if self.angle1+self.angle2+self.angle3 ==180:

return True

else:
return False
class
Equilateral(Triangle):
angle = 60
def __init__(self):
self.angle1 =
self.angle2 =
self.angle3 =
self.angle
my_triangle=Triangl
e(90,30,60)
print
my_triangle.number_
of_sides
3
print
my_triangle.check_a
ngles()
True
else:

return False

class Equilateral(Triangle):

angle = 60

def __init__(self):

self.angle1 = self.angle2 = self.angle3 = self.angle

my_triangle=Triangle(90,30,60)

print my_triangle.number_of_sides3

print my_triangle.check_angles()
True

Q10. Create a class variable named number_of_sides and set it equal to 3.

Solution:

class Triangle:

def __init__(self, angle1, angle2, angle3):

self.angle1 = angle1

self.angle2 = angle2

self.angle3 = angle3

self.number_of_sides = 3

def check_angles(self):

return self.angle1 + self.angle2 + self.angle3 == 180

my_triangle = Triangle(90, 30,60)

print(my_triangle.number_of_sides)

print(my_triangle.check_angles())

Output:

True

Q11. Create a method named check_angles. The sum of a triangle's three angles should returnTrue if the
sum is equal to 180, and False otherwise. The method should print whether theangles belong to a triangle
or not.11.1 Write methods to verify if the triangle is an acute triangle or obtuse triangle.11.2 Create an
instance of the triangle class and call all the defined methods.11.3 Create three child classes of triangle
class - isosceles_triangle, right_triangle andequilateral_triangle.11.4 Define methods which check for their
properties.

Solution:

class Triangle:

def __init__(self, a, b, c):

self.a, self.b, self.c = a, b, c

print(self.is_right_triangle())

def type_of_triangle(self):

if self.a < 90 and self.b < 90 and self.c < 90:

return "Acute"
return "Obtuse"

def is_right_triangle(self):

if sum((self.a, self.b, self.c)) == 180:

return True

return False

class Isosceles_triangle(Triangle):

def __init__(self, a, b, c):

super().__init__(a, b, c)

def check(self):

if self.a == self.b or self.b == self.c or self.c == self.a:

return True

return False

class Right_triangle(Triangle):

def __init__(self, a, b, c):

super().__init__(a, b, c)

def check(self):

if self.a == 90 or self.b == 90 or self.c == 90:

return True

return False

class Equilateral_triangle(Triangle):

def __init__(self, a, b, c):

super().__init__(a, b, c)

def check(self):

if self.a == self.b == self.c:

return True

return False

# TESTS:

t1 = Isosceles_triangle(60, 60, 60)

print(t1.check())

t2 = Right_triangle(90, 30, 60)

print(t2.check())
t3 = Equilateral_triangle(60, 60, 60)

print(t3.check())

t1 = Isosceles_triangle(70, 55, 55)

print(t1.check())

t2 = Right_triangle(60, 60, 60)

print(t2.check())

t3 = Equilateral_triangle(60, 59, 61)

print(t3.check())

Output:

True

True

True

True

True

True

True

True

True

False

True

False

Q12. Create a class isosceles_right_triangle which inherits from isosceles_triangle andright_triangle

12.1 Define methods which check for their properties.

Solution:

class Triangle{

public:

void triangle(){

cout<<"I am a triangle\n";
}};

class Isosceles : public Triangle{

public:

void isosceles(){

cout<<"I am an isosceles triangle\n";

//Write your code here.

void description(){

cout<<"In an isosceles triangle two sides are equal\n";

};

int main(){

Isosceles isc;

isc.isosceles();

isc.description();

isc.triangle();

return 0;

You might also like