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.
Solution:
class Employee:
def __init__(self):
self.EmployeeID = None
self.Gender = None
self.Salary = None
self.PerformanceRating = None
def get(self):
self.EmployeeID = int(input("Enter Employee ID: "))
self.Gender = input("Enter Gender: ")
self.Salary = float(input("Enter Salary: "))
self.PerformanceRating = float(input("Enter Performance Rating (Out of 5): "))
class JoiningDetails:
def __init__(self, DateofJoining):
self.DateofJoining = DateofJoining
def get_DoJ (self):
joining_date = input('Enter the Joining Date in YYYY-MM-DD format: ')
self.DateofJoining = datetime.strptime(joining_date, '%Y-%m-%d')
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:
# Constructor for the Vehicle class
def __init__(self, fare):
self.fare = fare
# Method to return the fare
def get_fare(self):
return self.fare
# Different types of vehicles
class Bus(Vehicle):
pass
class Car(Vehicle):
pass
class Train(Vehicle):
pass
class Truck(Vehicle):
pass
class Ship(Vehicle):
pass
# Create objects for each vehicle type
bus = Bus(50)
car = Car(40)
train = Train(150)
truck = Truck(80)
ship = Ship(200)
# Calculate the total fare using the polymorphic function 'get_fare'
total_fare = bus.get_fare() + car.get_fare() + train.get_fare() + truck.get_fare() + ship.get_fare()
print(f"Total fare for all vehicles: ${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:
def Max_Score(M):
# Initialize an empty dictionary to store total scores
total_scores = {}
max_individual_score = 0
max_score_player = ''
# Iterate through each test match in the dictionary
for test, scores in M.items():
for player, score in scores.items():
# If player is already in total_scores, add the score to their current score
# Else, initialize with their score for this match
total_scores[player] = total_scores.get(player, 0) + score
# Check if this individual score is the maximum so far
if score > max_individual_score:
max_individual_score = score
max_score_player = player
# Print the maximum individual score
print(f"The highest individual score is {max_individual_score} by {max_score_player}.")
# Find the player with the maximum score across all matches
top_player = max(total_scores, key=total_scores.get)
top_score = total_scores[top_player]
return top_player, top_score
# Test
M = {'test1':{'Dhoni':56, 'Balaji':85}, 'test2':{'Dhoni':87, 'Balaji':200}}
print(Max_Score(M))
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:
import random
suits = ['Heart', 'Diamond', 'Spade', 'Club']
card = {
'A' : 1,
'2' : 2,
'3' : 3,
'4' : 4,
'5' : 5,
'6' : 6,
'7' : 7,
'8' : 8,
'9' : 9,
'10' : 10,
'J' : 11,
'Q' : 12,
'K' : 13
key = list(card.keys())
final_deck = {}
for s in suits:
for k in key:
new_key = k + ' of ' + s
new_value = card[k]
final_deck[new_key] = new_value
final_deck_keys = list(final_deck.keys())
choice = []
for i in range(8):
chosen_card = random.choice(final_deck_keys)
choice.append(chosen_card)
final_deck_keys.remove(chosen_card)
initial_point = 0
for i in range(1,8):
print('Your current card is: ', choice[i-8])
inp = int(input('Predict the next card is higher or lower(Press 1 for lower, 2 for higher): '))
if (inp != 1) and (inp != 2):
print('Predict using keys 1 or 2 i.e Press 1 for lower, 2 for higher', inp)
break
else:
if final_deck[choice[i]] > final_deck[choice[i-1]]:
flag = 1
else:
flag = 2
if (inp == flag):
initial_point = initial_point + 20
else:
initial_point = initial_point - 15
print ('Your point is: ', initial_point)
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:
# Create an empty dictionary
car_0 = {
'color' : None,
'speed' : 'medium',
'x_position' : 10,
'y_position' : 72
# Fill the dictionary with given keys and values
#car_0['color'] = None # No color provided, so keeping it as None
#car_0['speed'] = 'medium'
#car_0['x_position'] = 10
#car_0['y_position'] = 72
# Modify the x_position based on speed value
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 the modified dictionary
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.
Solution:
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def printarea(self):
return 0
class Rectangle(Shape):
def _init_(self, length, breadth):
self.length = length
self.breadth = breadth
def printarea(self):
print(self.length * self.breadth)
class Square(Shape):
def _init_(self, side):
self.side = side
def printarea(self):
print(f'The area of the square is {self.side**2}')
8. 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:
n=1
a = []
while n!= 51:
a.append(n)
n=n+1
def square(a):
b = []
for element in a:
c = element**2
b.append(c)
print(b)
square(a)
9. Create a class, Triangle. Its init() method should take self, angle1, angle2, and angle3 as
arguments.
10. Create a class variable named number_of_sides and set it equal to 3.
11. 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.
Q12. Create a class isosceles_right_triangle which inherits from isosceles_triangle and
right_triangle.
12.1 Define methods which check for their properties.
Solution:
class Triangle():
def __init__(self, angle1, angle2, angle3):
self.angle1 = angle1
self.angle2 = angle2
self.angle3 = angle3
def check_angles(self):
sum = self.angle1 + self.angle2 + self.angle3
if (sum == 180):
print('Angles belong to Triangle')
return True
else:
print('Angles do not belong to Triangle')
return False
def type_of_triangle (self):
if self.angle1 < 90 and self.angle2 < 90 and self.angle3 < 90:
print ('The triangle is acute!')
elif self.angle1 > 90 or self.angle2 > 90 or self.angle3 > 90:
print ('The triangle is obtuse!')
else:
print('The triangle belong to Right Angled Triangle')
class Number_of_Sides(Triangle):
sides = 3
class Isosceles_triangle(Triangle):
def __init__(self, angle1, angle2, angle3, side1, side2, side3):
super().__init__(angle1, angle2, angle3)
self.side1 = side1
self.side2 = side2
self.side3 = side3
def check_iso_triangle(self):
if ((self.side1 == self.side2) or (self.side2 == self.side3) or (self.side1 == self.side3)) and
((self.angle1 == self.angle2) or (self.angle2 == self.angle3) or (self.angle1 == self.angle3)):
print('Triangle belongs to Isosceles family')
else:
print('The triangle do not belong to Isosceles family')
class Right_triangle(Triangle):
def __init__(self, angle1, angle2, angle3):
super().__init__ (angle1, angle2, angle3)
def check_right_triangle(self):
if (self.angle1 == 90) or (self.angle2 == 90) or (self.angle3 == 90):
print('The triangle is Right Angled Triangle')
else:
print('The triangle is not Right Angled Triangle')
class Equilateral_triangle(Triangle):
def __init__(self, angle1, angle2, angle3, side1, side2, side3):
super().__init__(angle1, angle2, angle3)
self.side1 = side1
self.side2 = side2
self.side3 = side3
def check_equilateral_triangle(self):
if ((self.side1 == self.side2) and (self.side2 == self.side3) and (self.side1 == self.side3)) and
((self.angle1 == self.angle2) and (self.angle2 == self.angle3) and (self.angle1 == self.angle3)):
print ('The triangle belongs to Equilateral Triangle family')
else:
print ('The triangle do not belong to Equlateral Triangle family')
class Isosceles_right_triangle(Isosceles_triangle, Right_triangle):
def __init__(self, angle1, angle2, angle3, side1, side2, side3):
super().__init__(angle1, angle2, angle3, side1, side2, side3)
def check_iso_right_triangle(self):
if ((self.side1 == self.side2) and (self.side2 == self.side3) and (self.side1 == self.side3)) and
((self.angle1 == self.angle2) and (self.angle2 == self.angle3) and (self.angle1 == self.angle3)):
print('The triangle belong to Isosceles Right Angle Triangle Triangle family')
else:
print('The triangle do not belong to Isosceles Right Angle Triangle Triangle family')