0% found this document useful (0 votes)
94 views

Assignment 2 Oops

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
94 views

Assignment 2 Oops

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

lOMoARcPSD|42225480

Assignment 2-oops

Python For Data Science (MIT School of Distance Education)

Scan to open on Studocu

Studocu is not sponsored or endorsed by any college or university


Downloaded by keerthu krish ([email protected])
lOMoARcPSD|42225480

16/10/2023, 22:02 Assignment2

In [ ]: ASSIGNMET 2 - Python OOPs Assignment

In [1]: 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 thes
the user.
2. JoiningDetail class has a data member DateOfJoining of type Date and a fu
getDoJ to get the Date of joining of employees.
3. Information Class uses the marks from Employee class and the DateOfJoinin
from the JoiningDetail class to calculate the top 3 Employees based on their
and then Display, using readData, all the details on these employees in Asce
order of their Date Of Joining.

ANS -
from datetime import date

class Employee:
def __init__(self):
self.EmployeeID = 0
self.Gender = ""
self.Salary = 0
self.PerformanceRating = 0

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

class JoiningDetail:
def __init__(self):
self.DateOfJoining = date.today()

def getDoJ(self):
year = int(input("Enter Year of Joining: "))
month = int(input("Enter Month of Joining: "))
day = int(input("Enter Day of Joining: "))
self.DateOfJoining = date(year, month, day)

class Information(Employee, JoiningDetail):


def __init__(self):
Employee.__init__(self)
JoiningDetail.__init__(self)

def readData(self, num_employees):


employees = []
for _ in range(num_employees):
employee = Information()
employee.get()
employee.getDoJ()
employees.append(employee)
return employees

def top3Employees(self, employees):


sorted_employees = sorted(employees, key=lambda x: x.PerformanceRati
return sorted_employees[:3]

def displayTop3(self, top_3_employees):


localhost:8888/nbconvert/html/Assignment2.ipynb?download=false 1/9
Downloaded by keerthu krish ([email protected])
lOMoARcPSD|42225480

16/10/2023, 22:02 Assignment2


sorted_employees = sorted(top_3_employees, key=lambda x: x.DateOfJoi
print("\nTop 3 Employees:")
for i, employee in enumerate(sorted_employees, 1):
print(f"\nEmployee {i}")
print(f"Employee ID: {employee.EmployeeID}")
print(f"Gender: {employee.Gender}")
print(f"Salary: {employee.Salary}")
print(f"Performance Rating: {employee.PerformanceRating}")
print(f"Date of Joining: {employee.DateOfJoining}")

if __name__ == "__main__":
num_employees = int(input("Enter the number of employees: "))
info = Information()
employees = info.readData(num_employees)
top_3_employees = info.top3Employees(employees)
info.displayTop3(top_3_employees)

Enter the number of employees: 2


Enter Employee ID: 100
Enter Gender: make
Enter Salary: 5000
Enter Performance Rating (out of 5): 4
Enter Year of Joining: 2015
Enter Month of Joining: 2
Enter Day of Joining: 1
Enter Employee ID: 101
Enter Gender: female
Enter Salary: 57800
Enter Performance Rating (out of 5): 5
Enter Year of Joining: 2020
Enter Month of Joining: 5
Enter Day of Joining: 1

Top 3 Employees:

Employee 1
Employee ID: 100
Gender: make
Salary: 5000.0
Performance Rating: 4
Date of Joining: 2015-02-01

Employee 2
Employee ID: 101
Gender: female
Salary: 57800.0
Performance Rating: 5
Date of Joining: 2020-05-01

In [2]: Q.2 Write a Python program to demonstrate Polymorphism.


1. Class Vehicle with a parameterized function Fare, that takes input value
returns it to calling Objects.
2. Create five separate variables Bus, Car, Train, Truck and Ship that call
function.
3. Use a third variable TotalFare to store the sum of fare for each Vehicle
4. Print the TotalFare.

class Vehicle:
def __init__(self, vehicle_type):
self.vehicle_type = vehicle_type

def Fare(self, fare):


return fare

localhost:8888/nbconvert/html/Assignment2.ipynb?download=false 2/9
Downloaded by keerthu krish ([email protected])
lOMoARcPSD|42225480

16/10/2023, 22:02 Assignment2


# Create instances of different vehicle types
bus = Vehicle("Bus")
car = Vehicle("Car")
train = Vehicle("Train")
truck = Vehicle("Truck")
ship = Vehicle("Ship")

# Calculate fares for each vehicle


bus_fare = bus.Fare(50.0)
car_fare = car.Fare(30.0)
train_fare = train.Fare(100.0)
truck_fare = truck.Fare(70.0)
ship_fare = ship.Fare(120.0)

# Calculate the total fare


total_fare = bus_fare + car_fare + train_fare + truck_fare + ship_fare

# Print the total fare


print(f"Total Fare for all vehicles: ${total_fare}")

Total Fare for all vehicles: $370.0

In [3]: Q3. Consider an ongoing test cricket series. Following are the names of the
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 bo
Create a python function Max_Score (M) that reads a dictionary M that recogn
with the highest total score. This function will return ( Top player , Total
consider the Top player as String who is the highest scorer and Top score as
Input : Max_Score({‘test1’:{‘Dhoni’:56, ‘Balaji : 85}, ‘test2’:{‘Dhoni’ 87,
Output : (‘Balaji ‘ , 200)

def Max_Score(scores):
top_player = ""
top_score = 0

for match_scores in scores.values():


for player, score in match_scores.items():
if score > top_score:
top_player = player
top_score = score

return (top_player, top_score)

# Example input
matches = {
'test1': {'Dhoni': 56, 'Balaji': 85},
'test2': {'Dhoni': 87, 'Balaji': 200}
}

result = Max_Score(matches)
print(result) # Output: ('Balaji', 200)

('Balaji', 200)

In [ ]: 4. Create a simple Card game in which there are 8 cards which are randomly c
deck. The first card is shown face up. The game asks the player to predict w
in the selection will have a higher or lower value than the currently showin

For example, say the card that’s shown is a 3. The player chooses “higher,”
shown. If that card has a higher value, the player is correct. In this examp
chosen “lower,” they would have been incorrect. If the player guesses correc
localhost:8888/nbconvert/html/Assignment2.ipynb?download=false 3/9
Downloaded by keerthu krish ([email protected])
lOMoARcPSD|42225480

16/10/2023, 22:02 Assignment2


points. If they choose incorrectly, they lose 15 points. If the next card to
same value as the previous card, the player is incorrect.

import random

# Initialize the deck with 8 cards


deck = [2, 3, 4, 5, 6, 7, 8, 9]

# Shuffle the deck


random.shuffle(deck)

# Initialize the score


score = 0

# Play the game


for i in range(7): # We play 7 rounds
current_card = deck[i]
print(f"Current card: {current_card}")

# Ask the player for their prediction


user_prediction = input("Predict 'higher' or 'lower': ").strip().lower()

# Randomly select the next card


next_card = deck[i + 1]

if next_card == current_card:
print("The next card has the same value. You are incorrect.")
score -= 15
elif (user_prediction == "higher" and next_card > current_card) or (user
print(f"The next card is {next_card}. You are correct.")
score += 20
else:
print(f"The next card is {next_card}. You are incorrect.")
score -= 15

# Display the final score


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

In [1]: Q5. Create an empty dictionary called Car_0 . Then fill the dictionary with
, 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
Print the modified dictionary

# Create an empty dictionary


car_0 = {}

# Fill the dictionary with keys and initial values


car_0['color'] = 'unknown' # You can set any color you like.
car_0['speed'] = 'medium'
car_0['X_position'] = 10
car_0['Y_position'] = 72

# Modify X_position based on speed


if car_0['speed'] == 'slow':
car_0['X_position'] += 2
elif car_0['speed'] == 'medium':
car_0['X_position'] += 9
localhost:8888/nbconvert/html/Assignment2.ipynb?download=false 4/9
Downloaded by keerthu krish ([email protected])
lOMoARcPSD|42225480

16/10/2023, 22:02 Assignment2


elif car_0['speed'] == 'fast':
car_0['X_position'] += 22

# Print the modified dictionary


print(car_0)

{'color': 'unknown', 'speed': 'medium', 'X_position': 19, 'Y_position': 72}

In [2]: Q6. Show a basic implementation of abstraction in python using the abstract
1. Create an abstract class in python.
2. Implement abstraction with the other classes and base class as abstract c

from abc import ABC, abstractmethod

# Abstract class definition


class Shape(ABC):

@abstractmethod
def area(self):
pass

# Concrete subclass 1
class Circle(Shape):
def __init__(self, radius):
self.radius = radius

def area(self):
return 3.1415 * self.radius * self.radius

# Concrete subclass 2
class Square(Shape):
def __init__(self, side_length):
self.side_length = side_length

def area(self):
return self.side_length * self.side_length

# Attempting to create an instance of the abstract class will result in a Ty


# shape = Shape() # This will raise a TypeError

# Create instances of the concrete subclasses


circle = Circle(5)
square = Square(4)

# Calculate and print the areas


print("Circle Area:", circle.area())
print("Square Area:", square.area())

Circle Area: 78.53750000000001


Square Area: 16

In [7]: Q7. Create a program in python to demonstrate Polymorphism.


1. Make use of private and protected members using python name mangling tech

class Animal:
def __init__(self, name, age=0): # Make 'age' optional with a default v
self._name = name # Protected member using a single underscore
self.__age = age # Private member using double underscore

def make_sound(self):
pass

def display_info(self):
localhost:8888/nbconvert/html/Assignment2.ipynb?download=false 5/9
Downloaded by keerthu krish ([email protected])
lOMoARcPSD|42225480

16/10/2023, 22:02 Assignment2


return f"{self._name} (Age: {self.__age})"

class Dog(Animal):
def make_sound(self):
return "Woof!"

class Cat(Animal):
def make_sound(self):
return "Meow!"

class Bird(Animal):
def make_sound(self):
return "Chirp!"

# Create instances of different animals


dog = Dog("Buddy")
cat = Cat("Whiskers", 2) # Provide 'name' and 'age'
bird = Bird("Tweetie")

# Demonstrate polymorphism
animals = [dog, cat, bird]

for animal in animals:


print(f"{animal.display_info()} says: {animal.make_sound()}")

Buddy (Age: 0) says: Woof!


Whiskers (Age: 2) says: Meow!
Tweetie (Age: 0) says: Chirp!

In [8]: 8. Given a list of 50 natural numbers from 1-50. Create a function that will
from the list and return the square of each element. Use the python map and
implement the function on the given list.

# Define a function to square a number


def square(x):
return x ** 2

# Create a list of natural numbers from 1 to 50


numbers = list(range(1, 51))

# Use map to apply the square function to each element in the list
squared_numbers = list(map(square, numbers))

# Print the squared numbers


print(squared_numbers)

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 3
24, 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, 202
5, 2116, 2209, 2304, 2401, 2500]

In [9]: Q9. Create a class, Triangle. Its init() method should take self, angle1, an
arguments.

class Triangle:
def __init__(self, angle1, angle2, angle3):
self.angle1 = angle1
self.angle2 = angle2
localhost:8888/nbconvert/html/Assignment2.ipynb?download=false 6/9
Downloaded by keerthu krish ([email protected])
lOMoARcPSD|42225480

16/10/2023, 22:02 Assignment2


self.angle3 = angle3

# Create an instance of the Triangle class


triangle = Triangle(60, 60, 60)

# Access the angles


print("Angle 1:", triangle.angle1)
print("Angle 2:", triangle.angle2)
print("Angle 3:", triangle.angle3)

Angle 1: 60
Angle 2: 60
Angle 3: 60

In [10]: Q10. Create a class variable named number_of_sides and set it equal to 3.

class Triangle:
number_of_sides = 3 # Class variable

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


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

# Access the class variable


print("Number of sides in a Triangle:", Triangle.number_of_sides)

Number of sides in a Triangle: 3

In [ ]: Q11. Create a method named check_angles. The sum of a triangle's three angle
True if the sum is equal to 180, and False otherwise. The method should prin
angles belong to a triangle or not.
11.1 Write methods to verify if the triangle is an acute triangle or obtuse
11.2 Create an instance of the triangle class and call all the defined metho
11.3 Create three child classes of triangle class - isosceles_triangle, righ
equilateral_triangle.
11.4 Define methods which check for their properties.

11-
class Triangle:
def __init__(self, angle1, angle2, angle3):
self.angle1 = angle1
self.angle2 = angle2
self.angle3 = angle3

def check_angles(self):
if self.angle1 + self.angle2 + self.angle3 == 180:
print("The angles belong to a triangle.")
return True
else:
print("The angles do not belong to a triangle.")
return False

# Create an instance of the Triangle class


triangle = Triangle(60, 60, 60)

# Call the check_angles method


triangle.check_angles()

localhost:8888/nbconvert/html/Assignment2.ipynb?download=false 7/9
Downloaded by keerthu krish ([email protected])
lOMoARcPSD|42225480

16/10/2023, 22:02 Assignment2

11.1
class Triangle:
# ... (previous code) ...

def is_acute(self):
if all(angle < 90 for angle in [self.angle1, self.angle2, self.angle
return True
return False

def is_obtuse(self):
if any(angle > 90 for angle in [self.angle1, self.angle2, self.angle
return True
return False

11.2-
# Create an instance of the Triangle class
triangle = Triangle(60, 60, 60)

# Call the check_angles method


print("Check Angles Result:", triangle.check_angles())
print("Is Acute Triangle:", triangle.is_acute())
print("Is Obtuse Triangle:", triangle.is_obtuse())

11.3-
class IsoscelesTriangle(Triangle):
def __init__(self, angle1, angle2):
super().__init__(angle1, angle2, 180 - (angle1 + angle2))

class RightTriangle(Triangle):
def __init__(self, angle1, angle2):
super().__init__(angle1, angle2, 90)

class EquilateralTriangle(Triangle):
def __init__(self, angle):
super().__init__(angle, angle, angle)

11.4 -
class Triangle:
# ... (previous code) ...

def is_equilateral(self):
if self.angle1 == self.angle2 == self.angle3:
return True
return False

class IsoscelesTriangle(Triangle):
def is_isosceles(self):

localhost:8888/nbconvert/html/Assignment2.ipynb?download=false 8/9
Downloaded by keerthu krish ([email protected])
lOMoARcPSD|42225480

16/10/2023, 22:02 Assignment2


if self.angle1 == self.angle2 or self.angle2 == self.angle3 or self.
return True
return False

class RightTriangle(Triangle):
def is_right_triangle(self):
if any(angle == 90 for angle in [self.angle1, self.angle2, self.angl
return True
return False

# Create instances of child classes


isosceles = IsoscelesTriangle(45, 45)
right = RightTriangle(30, 60)
equilateral = EquilateralTriangle(60)

# Check their properties


print("Is Isosceles Triangle:", isosceles.is_isosceles())
print("Is Right Triangle:", right.is_right_triangle())
print("Is Equilateral Triangle:", equilateral.is_equilateral())

In [3]: Q12. Create a class isosceles_right_triangle which inherits from isosceles_t


right_triangle.
12.1 Define methods which check for their properties.

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

class IsoscelesTriangle(Triangle):
def is_isosceles(self):
if self.angle1 == self.angle2 or self.angle2 == self.angle3 or self.
return True
return False

class RightTriangle(Triangle):
def is_right_triangle(self):
if any(angle == 90 for angle in [self.angle1, self.angle2, self.angl
return True
return False

class IsoscelesRightTriangle(IsoscelesTriangle, RightTriangle):


def __init__(self, angle1, angle2):
super().__init__(angle1, angle2, 180 - (angle1 + angle2))

def is_isosceles_right_triangle(self):
return self.is_isosceles() and self.is_right_triangle()

# Create an instance of IsoscelesRightTriangle


isosceles_right = IsoscelesRightTriangle(45, 45)

# Check its properties


print("Is Isosceles Right Triangle:", isosceles_right.is_isosceles_right_tri

Is Isosceles Right Triangle: True

localhost:8888/nbconvert/html/Assignment2.ipynb?download=false 9/9
Downloaded by keerthu krish ([email protected])

You might also like