Python - Develop an inheritance hierarchy based upon a Polygon class that has abstract methods area( ) and perimeter( ). Implement classes Triangle, Quadrilateral, Pentagon, that extend this base class, with the obvious meanings for the area( ) and perimeter( ) methods. Write a simple program that allows users to create polygons of the various types and input their geometric dimensions, and the program then outputs their area and perimeter.
Develop an inheritance hierarchy based upon a Polygon class that has abstract methods area( ) and perimeter( ). Implement classes Triangle, Quadrilateral, Pentagon, that extend this base class, with the obvious meanings for the area( ) and perimeter( ) methods. Write a simple program that allows users to create polygons of the various types and input their geometric dimensions, and the program then outputs their area and perimeter.
import math
from abc import ABC, abstractmethod
class Polygon(ABC):
"""Abstract base class for all polygons."""
def __init__(self, sides):
self.sides = sides
@abstractmethod
def area(self):
"""Calculates and returns the area of the polygon."""
pass
@abstractmethod
def perimeter(self):
"""Calculates and returns the perimeter of the polygon."""
pass
class Triangle(Polygon):
"""Represents a triangle, extending the Polygon class."""
def __init__(self, s1, s2, s3):
super().__init__([s1, s2, s3])
self.s1, self.s2, self.s3 = s1, s2, s3
def area(self):
# Using Heron's formula for the area
s = self.perimeter() / 2
return math.sqrt(s * (s - self.s1) * (s - self.s2) * (s - self.s3))
def perimeter(self):
return sum(self.sides)
class Quadrilateral(Polygon):
"""Represents a quadrilateral (assumed to be a rectangle for simplicity of area calculation)."""
def __init__(self, length, width):
# For simplicity, assuming a rectangle where all side lengths are not strictly required in list
super().__init__([length, width, length, width])
self.length, self.width = length, width
def area(self):
return self.length * self.width
def perimeter(self):
return 2 * (self.length + self.width)
class Pentagon(Polygon):
"""Represents a regular pentagon, extending the Polygon class."""
def __init__(self, side_length):
# A regular pentagon has 5 equal sides
super().__init__([side_length] * 5)
self.side_length = side_length
def area(self):
# Formula for the area of a regular pentagon: A = (1/4) * sqrt(5 * (5 + 2 * sqrt(5))) * a^2
return 0.25 * math.sqrt(5 * (5 + 2 * math.sqrt(5))) * (self.side_length ** 2)
def perimeter(self):
return sum(self.sides)
def create_polygon_from_user_input():
"""Allows users to select a polygon and input dimensions."""
print("Select a polygon type:")
print("1. Triangle")
print("2. Quadrilateral (Rectangle)")
print("3. Regular Pentagon")
choice = input("Enter your choice (1, 2, or 3): ")
try:
if choice == '1':
s1 = float(input("Enter side 1 length: "))
s2 = float(input("Enter side 2 length: "))
s3 = float(input("Enter side 3 length: "))
if s1 + s2 <= s3 or s1 + s3 <= s2 or s2 + s3 <= s1:
print("Error: The provided side lengths do not form a valid triangle.")
return None
return Triangle(s1, s2, s3)
elif choice == '2':
length = float(input("Enter length: "))
width = float(input("Enter width: "))
return Quadrilateral(length, width)
elif choice == '3':
side_length = float(input("Enter side length: "))
return Pentagon(side_length)
else:
print("Invalid choice.")
return None
except ValueError:
print("Invalid input. Please enter numeric values.")
return None
if __name__ == "__main__":
polygon = create_polygon_from_user_input()
if polygon:
print(f"\nCalculated Area: {polygon.area():.2f}")
print(f"Calculated Perimeter: {polygon.perimeter():.2f}")
Comments
Post a Comment