Manish Shukla-OOPS Assignment-M
Manish Shukla-OOPS Assignment-M
class Employee:
def __init__(self):
self.EmployeeID = ""
self.Gender = ""
self.Salary = 0
self.PerformanceRating = 0
def get(self):
self.EmployeeID = input("Enter Employee ID: ")
self.Gender = input("Enter Gender: ")
self.Salary = int(input("Enter Salary: "))
self.PerformanceRating = int(input("Enter Performance Rating (Out of 5): "))
class JoiningDetail:
def __init__(self):
self.DateOfJoining = datetime.now()
def getDoJ(self):
date_str = input("Enter Date of Joining (YYYY-MM-DD): ")
self.DateOfJoining = datetime.strptime(date_str, '%Y-%m-%d')
def readData(self):
num_employees = int(input("Enter number of employees: "))
for _ in range(num_employees):
emp = Employee()
emp.get()
join_detail = JoiningDetail()
join_detail.getDoJ()
self.employees.append((emp, join_detail))
def top_3_employees(self):
sorted_employees = sorted(self.employees, key=lambda x: x[0].PerformanceRating,
reverse=True)
top_3 = sorted_employees[:3]
top_3.sort(key=lambda x: x[1].DateOfJoining)
print("\nTop 3 Employees:")
for emp, join_detail in top_3:
print(f"Employee ID: {emp.EmployeeID}")
print(f"Gender: {emp.Gender}")
print(f"Salary: {emp.Salary}")
print(f"Performance Rating: {emp.PerformanceRating}")
print(f"Date of Joining: {join_detail.DateOfJoining}\n")
# Example usage:
if __name__ == "__main__":
info = Information()
info.readData()
info.top_3_employees()
class Vehicle:
def Fare(self, fare):
return fare
# Create instances of Vehicle subclasses
bus = Vehicle()
car = Vehicle()
train = Vehicle()
truck = Vehicle()
ship = Vehicle()
# Calculate fare for each vehicle
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)
# Calculate total fare
total_fare = bus_fare + car_fare + train_fare + truck_fare + ship_fare
print("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)
def Max_Score(M):
max_score = 0
top_player = ""
# Example usage:
M={
'test1': {'Dhoni': 56, 'Balaji': 85},
'test2': {'Dhoni': 87, 'Balaji': 200}
}
result = Max_Score(M)
print("Top player and Total Score:", 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.
import random
class CardGame:
def __init__(self):
self.deck = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] * 4
self.score = 0
def play_round(self):
# Shuffle the deck
random.shuffle(self.deck)
# Show the first card
current_card = self.deck.pop()
print("Current card:", current_card)
# Ask the player for their prediction
prediction = input("Predict if the next card will be 'higher' or 'lower': ").lower()
# Show the next card
next_card = self.deck.pop()
print("Next card:", next_card)
# Check if prediction is correct
if (prediction == 'higher' and next_card > current_card) or (prediction == 'lower' and next_card
< current_card):
self.score += 20
print("Correct! You gain 20 points.")
else:
self.score -= 15
print("Incorrect! You lose 15 points.")
# Check if next card has the same value as the previous card
if next_card == current_card:
self.score -= 15
print("The next card has the same value as the previous card. You lose an additional 15
points.")
print("Your current score:", self.score)
# Play the game
def main():
game = CardGame()
for _ in range(8):
game.play_round()
if __name__ == "__main__":
main()
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.
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.
class Vehicle:
def __init__(self, brand):
self._brand = brand # protected attribute
self.__mileage = 0 # private attribute with name mangling
def set_mileage(self, mileage):
self.__mileage = mileage
def get_mileage(self):
return self.__mileage
def display_info(self):
print(f"Brand: {self._brand}, Mileage: {self.__mileage}")
class Car(Vehicle):
def __init__(self, brand, model):
super().__init__(brand)
self.__model = model # private attribute with name mangling
def display_info(self):
print(f"Brand: {self._brand}, Model: {self.__model}, Mileage: {self.get_mileage()}")
class Truck(Vehicle):
def __init__(self, brand, capacity):
super().__init__(brand)
self.__capacity = capacity # private attribute with name mangling
def display_info(self):
print(f"Brand: {self._brand}, Capacity: {self.__capacity} tons, Mileage: {self.get_mileage()}")
# Create instances of Car and Truck
car = Car("Toyota", "Corolla")
car.set_mileage(30000)
truck = Truck("Ford", 5)
truck.set_mileage(50000)
# Display information using polymorphism
car.display_info()
truck.display_info()
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.
def square(x):
return x ** 2
numbers = list(range(1, 51))
squared_numbers = map(square, numbers)
filtered_squares = filter(lambda x: True, squared_numbers)
print(list(filtered_squares))
Q9. Create a class, Triangle. Its init() method should take self, angle1, angle2, and
angle3 as arguments.
class Triangle:
def __init__(self, angle1, angle2, angle3):
self.angle1 = angle1
self.angle2 = angle2
self.angle3 = angle3
# Example usage:
triangle = Triangle(60, 60, 60)
print("Angles of the triangle:", triangle.angle1, triangle.angle2, triangle.angle3)
class Shape:
number_of_sides = 3
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.
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
# Checks:
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())
class IsoscelesTriangle:
def __init__(self, base, side):
self.base = base
self.side = side
def is_isosceles(self):
return self.base == self.side
class RightTriangle:
def __init__(self, base, height, hypotenuse):
self.base = base
self.height = height
self.hypotenuse = hypotenuse
def is_right(self):
return self.base ** 2 + self.height ** 2 == self.hypotenuse ** 2
def check_properties(self):
is_iso = self.is_isosceles()
is_right = self.is_right()
if is_iso and is_right:
print("This triangle is an Isosceles Right Triangle.")
else:
print("This triangle is not an Isosceles Right Triangle.")
# Example usage:
triangle = IsoscelesRightTriangle(3, 3, 4)
triangle.check_properties()