Python OOPs Assignment
Q1. Write a Python program to demonstrate multiple inheritance.
1. Employee class has 3 data members EmployeeID, Gender (String), Salary and
PerformanceRating(Out of 5) of type int. It has a get() function to get these details from the user.
2. JoiningDetail 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.
Answer:
from datetime import datetime
#Base class: Employee
class Employee:
def __init__(self):
[Link] = None
[Link] = None
[Link] = None
[Link] = None
def get(self):
[Link] = input("Enter Employee ID: ")
[Link] = input("Enter Gender: ")
[Link] = int(input("Enter Salary: "))
[Link] = int(input("Enter Performance Rating (out of 5): "))
# Base class: JoiningDetail
class JoiningDetail:
def __init__(self):
[Link] = None
def getDoJ(self):
date_str = input("Enter Date of Joining (YYYY-MM-DD): ")
[Link] = [Link](date_str, '%Y-%m-%d')
# Derived class: Information
class Information(Employee, JoiningDetail):
def __init__(self):
Employee.__init__(self)
JoiningDetail.__init__(self)
def readData(self, employees):
# Sort employees by performance rating (descending) and date of joining (ascending)
sorted_employees = sorted(
employees,
key=lambda x: (-[Link], [Link])
# Select top 3 employees
top_employees = sorted_employees[:3]
# Display details of top employees
print("\nTop 3 Employees:")
for emp in top_employees:
print(f"EmployeeID: {[Link]}, Gender: {[Link]}, Salary: {[Link]}, "
f"Performance Rating: {[Link]}, Date Of Joining: {[Link]('%Y-
%m-%d')}")
# Main program
if __name__ == "__main__":
num_employees = int(input("Enter the number of employees: "))
employees = []
for _ in range(num_employees):
emp = Information()
print("\nEnter Employee Details:")
[Link]()
[Link]()
[Link](emp)
# Create an instance of Information to calculate and display the top employees
info = Information()
[Link](employees)
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.
Answer:
# Base class: Vehicle
class Vehicle:
def Fare(self, fare):
return fare
# Main program
if __name__ == "__main__":
# Creating instances of Vehicle for each type
Bus = Vehicle()
Car = Vehicle()
Train = Vehicle()
Truck = Vehicle()
Ship = Vehicle()
# Assigning fare to each vehicle type using the Fare method
bus_fare = [Link](100)
car_fare = [Link](200)
train_fare = [Link](150)
truck_fare = [Link](250)
ship_fare = [Link](300)
# Calculating the total fare
TotalFare = bus_fare + car_fare + train_fare + truck_fare + ship_fare
# Printing the total fare
print(f"Total Fare for all vehicles: {TotalFare}")
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)
Answer:
def Max_Score(M):
total_scores = {}
for test, scores in [Link]():
for player, score in [Link]():
total_scores[player] = total_scores.get(player, 0) + score
top_player = max(total_scores, key=total_scores.get)
top_score = total_scores[top_player]
return (top_player, top_score)
# Input dictionary
matches = {
'test1': {'Dhoni': 56, 'Balaji': 85},
'test2': {'Dhoni': 87, 'Balaji': 200}
result = Max_Score(matches)
print(result)
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.
Answer:
import random
def create_deck():
"""Creates a deck of cards with values 1 to 13 for each suit."""
suits = ['Hearts', 'Diamonds', 'Clubs', 'Spades']
deck = []
for suit in suits:
for value in range(1, 14):
[Link]((value, suit))
return deck
def play_game():
# Create and shuffle the deck
deck = create_deck()
[Link](deck)
# Select 8 random cards for the game
selected_cards = [Link](deck, 8)
print("Welcome to the Higher or Lower Card Game!")
score = 0
current_card = selected_cards[0]
print(f"The first card is: {current_card[0]} of {current_card[1]}")
# Loop through the remaining cards
for i in range(1, len(selected_cards)):
next_card = selected_cards[i]
guess = input("Will the next card be higher or lower? (Enter 'higher' or 'lower'): ").lower()
# Determine if the guess is correct
if next_card[0] > current_card[0]:
correct = "higher"
elif next_card[0] < current_card[0]:
correct = "lower"
else:
correct = None # Same value is an incorrect guess
if correct and guess == correct:
print(f"Correct! The next card is {next_card[0]} of {next_card[1]}")
score += 20
else:
print(f"Incorrect! The next card is {next_card[0]} of {next_card[1]}")
score -= 15
# Update the current card
current_card = next_card
# Display the current score
print(f"Your current score is: {score}\n")
# End of game
print(f"Game over! Your final score is: {score}")
# Start the game
play_game()
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.
Answer:
car_0 = {}
car_0 = {'x_position': 10, 'y_position': 72, 'speed': 'medium'}
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)
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.
Answer:
from abc import ABC, abstractmethod
# Abstract class
class Animal(ABC):
@abstractmethod
def sound(self):
"""Abstract method for animal sound"""
pass
@abstractmethod
def habitat(self):
"""Abstract method for animal habitat"""
pass
class Dog(Animal):
def sound(self):
return "Bark"
def habitat(self):
return "Domestic"
class Dolphin(Animal):
def sound(self):
return "Click"
def habitat(self):
return "Aquatic"
dog = Dog()
dolphin = Dolphin()
print("Dog makes sound:", [Link]())
print("Dog lives in:", [Link]())
print("Dolphin makes sound:", [Link]())
print("Dolphin lives in:", [Link]())
Q7. Create a program in python to demonstrate Polymorphism.
1. Make use of private and protected members using python name mangling techniques.
Answer:
# Base class
class Animal:
def __init__(self, name):
self._species = "Generic Animal" # Protected member
self.__name = name # Private member
def sound(self):
"""General sound method"""
return "Some generic animal sound"
def get_name(self):
"""Access private member"""
return self.__name
# Derived class: Dog
class Dog(Animal):
def __init__(self, name):
super().__init__(name)
self._species = "Dog"
def sound(self):
"""Overriding sound method"""
return "Bark"
# Derived class: Cat
class Cat(Animal):
def __init__(self, name):
super().__init__(name)
self._species = "Cat"
def sound(self):
"""Overriding sound method"""
return "Meow"
# Polymorphism demonstration
def describe_animal(animal):
print(f"Species: {animal._species}") # Access protected member
print(f"Name: {animal.get_name()}") # Access private member using a method
print(f"Sound: {[Link]()}") # Polymorphic behavior
print("-" * 30)
# Creating objects of different classes
dog = Dog("Buddy")
cat = Cat("Whiskers")
# Calling the describe_animal function
describe_animal(dog)
describe_animal(cat)
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.
Answer:
# Define a function to calculate the square of a number
def square(num):
return num ** 2
# Create a list of natural numbers from 1 to 50
numbers = list(range(1, 51))
# Use the map function
squared_numbers = list(map(square, numbers))
# Output the squared numbers
print("Squared Numbers:")
print(squared_numbers)
Q9. Create a class, Triangle. Its init() method should take self, angle1, angle2, and angle3 as
arguments.
Answer:
class Triangle:
def __init__(self, angle1, angle2, angle3):
self.angle1 = angle1
self.angle2 = angle2
self.angle3 = angle3
self.total_angles = 180 # Sum of angles in any triangle
def is_valid_triangle(self):
return self.angle1 + self.angle2 + self.angle3 == self.total_angles
def triangle_type(self):
if not self.is_valid_triangle():
return "Invalid Triangle"
if self.angle1 < 90 and self.angle2 < 90 and self.angle3 < 90:
return "Acute Triangle"
elif self.angle1 == 90 or self.angle2 == 90 or self.angle3 == 90:
return "Right Triangle"
else:
return "Obtuse Triangle"
# Example Usage
triangle1 = Triangle(60, 60, 60)
triangle2 = Triangle(90, 45, 45)
triangle3 = Triangle(120, 30, 30)
print(f"Triangle1 is valid: {triangle1.is_valid_triangle()}, Type: {triangle1.triangle_type()}")
print(f"Triangle2 is valid: {triangle2.is_valid_triangle()}, Type: {triangle2.triangle_type()}")
print(f"Triangle3 is valid: {triangle3.is_valid_triangle()}, Type: {triangle3.triangle_type()}")
Q10. Create a class variable named number_of_sides and set it equal to 3.
Answer:
class Triangle:
number_of_sides = 3
def __init__(self, angle1, angle2, angle3):
self.angle1 = angle1
self.angle2 = angle2
self.angle3 = angle3
def is_valid_triangle(self):
return self.angle1 + self.angle2 + self.angle3 == 180
# Example Usage
triangle = Triangle(60, 60, 60)
print(f"Number of sides in a triangle: {Triangle.number_of_sides}")
print(f"Is the triangle valid? {triangle.is_valid_triangle()}")
Q11. Create a method named check_angles. The sum of a triangle's three angles should return
True if the sum is equal to 180, and False otherwise. The method should print whether the angles
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 and
equilateral_triangle.
11.4 Define methods which check for their properties.
Answer:
11.1 and 11.2
class Triangle:
# Initialize the triangle with three angles
def __init__(self, angle1, angle2, angle3):
self.angle1 = angle1
self.angle2 = angle2
self.angle3 = angle3
# Method to check if the sum of the angles is equal to 180
def check_angles(self):
if self.angle1 + self.angle2 + self.angle3 == 180:
print("The angles belong to a valid triangle.")
return True
else:
print("The angles do not belong to a valid triangle.")
return False
# Method to check if the triangle is acute
def is_acute_triangle(self):
if self.angle1 < 90 and self.angle2 < 90 and self.angle3 < 90:
print("The triangle is an Acute triangle.")
return True
return False
# Method to check if the triangle is obtuse
def is_obtuse_triangle(self):
if self.angle1 > 90 or self.angle2 > 90 or self.angle3 > 90:
print("The triangle is an Obtuse triangle.")
return True
return False
# Step 2: Create an instance of the triangle class and call all methods
triangle = Triangle(60, 60, 60)
triangle.check_angles()
triangle.is_acute_triangle()
triangle.is_obtuse_triangle()
11.3
class IsoscelesTriangle(Triangle):
def __init__(self, angle1, angle2, angle3):
super().__init__(angle1, angle2, angle3)
# Method to check if the triangle is an isosceles triangle (two angles are equal)
def is_isosceles(self):
if self.angle1 == self.angle2 or self.angle2 == self.angle3 or self.angle1 == self.angle3:
print("The triangle is an Isosceles triangle.")
return True
return False
class RightTriangle(Triangle):
def __init__(self, angle1, angle2, angle3):
super().__init__(angle1, angle2, angle3)
# Method to check if the triangle is a right triangle (one angle is 90 degrees)
def is_right_triangle(self):
if 90 in [self.angle1, self.angle2, self.angle3]:
print("The triangle is a Right triangle.")
return True
return False
class EquilateralTriangle(Triangle):
def __init__(self, angle1, angle2, angle3):
super().__init__(angle1, angle2, angle3)
# Method to check if the triangle is equilateral (all angles are 60 degrees)
def is_equilateral(self):
if self.angle1 == 60 and self.angle2 == 60 and self.angle3 == 60:
print("The triangle is an Equilateral triangle.")
return True
return False
11.4
# Creating instances of each triangle type
# For Equilateral Triangle
equilateral_triangle = EquilateralTriangle(60, 60, 60)
equilateral_triangle.check_angles()
equilateral_triangle.is_equilateral()
# For Isosceles Triangle
isosceles_triangle = IsoscelesTriangle(70, 70, 40)
isosceles_triangle.check_angles()
isosceles_triangle.is_isosceles()
# For Right Triangle
right_triangle = RightTriangle(90, 45, 45)
right_triangle.check_angles()
right_triangle.is_right_triangle()
# For a general Triangle
general_triangle = Triangle(80, 50, 50)
general_triangle.check_angles()
general_triangle.is_acute_triangle()
general_triangle.is_obtuse_triangle()
Q12. Create a class isosceles_right_triangle which inherits from isosceles_triangle and
right_triangle. 12.1 Define methods which check for their properties
Answer:
class Triangle:
def __init__(self, angle1, angle2, angle3):
[Link] = [angle1, angle2, angle3]
def check_angles(self):
return sum([Link]) == 180
class IsoscelesTriangle(Triangle):
def is_isosceles(self):
return len(set([Link])) <= 2
class RightTriangle(Triangle):
def is_right_triangle(self):
return 90 in [Link]
class IsoscelesRightTriangle(IsoscelesTriangle, RightTriangle):
def is_isosceles_right_triangle(self):
return self.is_right_triangle() and self.is_isosceles()
# Testing
isosceles_right = IsoscelesRightTriangle(90, 45, 45)
print(isosceles_right.check_angles()) # True
print(isosceles_right.is_isosceles_right_triangle()) # True
not_isosceles_right = IsoscelesRightTriangle(60, 60, 60)
print(not_isosceles_right.check_angles()) # True
print(not_isosceles_right.is_isosceles_right_triangle()) # False