Hey guys I'm trying to find out the area of the triangle using the Heron's formula i.e area= sqrt(s(s-l1)(s-l2)(s-l3)). For this, I need to check if the given sides add up to the triangle, which I have.
However, I'm not able to figure out how to use this in the inherited class here.
What, I want to do is take input from the parent class and calculate area from the inherited class. Any help is appreciated.
Nomenclature used 1) l1, l2, l3 : sides of the triangle 2) Checktri method is used to check if the given sides add up to a triangle or not 3) Areatri is the inherited class of Triangledim wherein the area need to be found out
import math
class Triangledim:
def __init__(self, l1, l2, l3):
self.l1 = l1
self.l2 = l2
self.l3 = l3
#Check if the given measurements form a triangle
def checktri(self):
if (self.l1+self.l2>self.l3) & (self.l2+self.l3>self.l1) & (self.l1+self.l3>self.l2):
s = (self.l1 +self.l2+self.l3)/2
return ("Perimeter of the triangle is %f" %s)
else :
return("not the right triangle proportions")
class Areatri(Triangledim):
def __init__(self):
Triangledim.__init__(self)
area = math.sqrt(self.s(self.s-self.l1)(self.s-self.l2)(self.s-self.l3))
return area
p=Triangledim(7,5,10)
The following code is what you probably need:
import math
class Triangledim():
def __init__(self, l1, l2, l3):
self.l1 = l1
self.l2 = l2
self.l3 = l3
self.s = (self.l1+self.l2+self.l3) / 2.0
def checktri(self):
if (self.l1+self.l2>self.l3) and (self.l2+self.l3>self.l1) and (self.l1+self.l3>self.l2):
print("Perimeter of the triangle is: {}".format(self.s))
else:
print("not the right triangle proportions")
def findArea(self):
area = math.sqrt(self.s*(self.s-self.l1)*(self.s-self.l2)*(self.s-self.l3))
print("The area of the triangle is: {}".format(area))
if __name__ == "__main__":
p = Triangledim(7,5,10)
p.checktri()
p.findArea()
Output:
Perimeter of the triangle is: 11.0
The area of the triangle is: 16.24807680927192
In case you want to use heritage, the following will do the job for you:
import math
class Triangledim():
def __init__(self, l1, l2, l3):
self.l1 = l1
self.l2 = l2
self.l3 = l3
self.s = (self.l1+self.l2+self.l3) / 2.0
def checktri(self):
if (self.l1+self.l2>self.l3) and (self.l2+self.l3>self.l1) and (self.l1+self.l3>self.l2):
print("Perimeter of the triangle is: {}".format(self.s))
else:
print("not the right triangle proportions")
class Areatri(Triangledim):
def findArea(self):
area = math.sqrt(self.s*(self.s-self.l1)*(self.s-self.l2)*(self.s-self.l3))
print("The area of the triangle is: {}".format(area))
if __name__ == "__main__":
p = Areatri(7,5,10)
p.checktri()
p.findArea()
Output:
Perimeter of the triangle is: 11.0
The area of the triangle is: 16.24807680927192