This is me with another project for beginners :)
The Project as stated by ZZucker about 2 months ago:
"Given the length of three sides, write a function that checks if it is
possible to create a triangle."
I could solve it with an annonymus function like this:

is_triangle = lambda a,b,c: a+b!=c and a+c!=b and b+c!=a and c-b<a<c+b

But as I'm trying to understand using "class"es, I did code the following
class.
Now, Is this an acceptable class?
Thank you in advance for your comments :)

#from math import*

class Triangle(object):
    """Checks if given sides can make a Triangle then shows the Angles."""
    def __init__(self, a, b, c):
        self.a = a
        self.b = b
        self.c = c
        self.A = self.B = self.C = 0

    def _istriangle(self):
        """Checks if given sides can make a Triangle"""
        if self.a+self.b!=self.c and self.a+self.c!=self.b and self.b+self.c!=self.a and self.c-self.b < self.a < self.c+self.b:
            return True
        else: return False

    def get_angles(self):
        """Calculates the Angles based on the Cosine Rule."""
        if self._istriangle():
            self.A = degrees(acos((self.b**2+self.c**2-self.a**2)/float(2*self.b*self.c)))
            self.B = degrees(acos((self.a**2+self.c**2-self.b**2)/float(2*self.a*self.c)))
            self.C = 180 - (self.A+self.B)
            print "It is a Triangle!"
            print "Angles Are:\nA: %.2f\nB: %.2f\nC: %.2f" %(self.A,self.B,self.C)
        else: print "Not-A-Triangle"


if __name__ == '__main__':
    a,b,c =  (float(x) for x in raw_input("Enter Sides(Separated by a Space): ").split())
    t = Triangle(a,b,c)
    t.get_angles()

Recommended Answers

All 4 Replies

Your triangle condition is false as (-1, 4, 2) would be a triangle. A correct condition is simply abs(b-c) < a < b+c. I would check 'triangulity' at object creation and raise ValueError if it fails

#from math import*

class Triangle(object):
    """Checks if given sides can make a Triangle then shows the Angles."""
    def __init__(self, a, b, c):
        self.a = a
        self.b = b
        self.c = c
        self._check_triangle()

    def _check_triangle(self):
        """Checks if given sides can make a Triangle"""
        if not(abs(self.b - self.c) < self.a < self.b + self.c):
            raise ValueError("Not a triangle")

    def get_angles(self):
        """Calculates the Angles based on the Cosine Rule."""
        A = degrees(acos((self.b**2+self.c**2-self.a**2)/float(2*self.b*self.c)))
        B = degrees(acos((self.a**2+self.c**2-self.b**2)/float(2*self.a*self.c)))
        C = 180 - (self.A+self.B)
        return A, B, C

Also with a method name like get_angles(), one expects that the method computes and returns a tuple of angles, and not that it prints something. Usable methods don't print anything, they return values.

commented: Thanks for this:) +4

Thanks for this informing comment, Gribouillis.
I corrected iter and added one more function.
any further guide is appreciated.

#from math import*

class Triangle(object):
    """Checks if given sides can make a Triangle then shows the Angles."""
    def __init__(self, a, b, c):
        self.a = a
        self.b = b
        self.c = c
        self.triangletype = ""
        self.A = self.B = self.C = 0
        self.__check_triangle()

    def __check_triangle(self):
        """Checks if given sides can make a Triangle"""
        if not (abs(self.c-self.b) < self.a < self.c+self.b):
            raise ValueError("Not a Triangle!")

    def get_angles(self):
        """Calculates the Angles based on the Cosine Rule."""
        self.A = degrees(acos((self.b**2+self.c**2-self.a**2)/float(2*self.b*self.c)))
        self.B = degrees(acos((self.a**2+self.c**2-self.b**2)/float(2*self.a*self.c)))
        self.C = 180 - (self.A+self.B)
        return self.A, self.B, self.C

    def triangle_type(self):
        """Gets the type of Triangle."""
        if self.A == 90 or self.B == 90 or self.C == 90:
            self.triangletype = "Right"
        elif self.a == self.b == self.c:
            self.triangletype = "Equilateral"
        elif (self.A == self.B or self.A == self.C or self.C == self.B):
            self.triangletype = "Isosceles"
        else:
            self.triangletype = "Scalene"

        return self.triangletype



if __name__ == '__main__':
    a,b,c =  (float(x) for x in raw_input("Enter Sides(Separated by a Space): ").split())
    t = Triangle(a,b,c)
    print "A: %.2f\nB: %.2f\nC: %.2f"%t.get_angles()
    print t.triangle_type()

The code could be massaged for example like this:

from math import *

class Triangle(object):
    """Checks if given sides can make a Triangle then shows the Angles."""
    def __init__(self, a, b, c):
        self.__check_triangle(a,b,c)
        self.a = a
        self.b = b
        self.c = c
        self.calculate_angles()

    def __check_triangle(self,a,b,c):
        """Checks if given sides can make a Triangle"""
        if not (abs(c-b) < a < c +b):
            raise ValueError("Not a Triangle!")

    def calculate_angles(self):
        """Calculates the Angles based on the Cosine Rule."""
        self.A = degrees(acos((self.b**2+self.c**2-self.a**2)/float(2*self.b*self.c)))
        self.B = degrees(acos((self.a**2+self.c**2-self.b**2)/float(2*self.a*self.c)))
        self.C = 180 - (self.A+self.B)

    @property
    def triangle_type(self):
        """Gets the type of Triangle."""
        if self.A == 90 or self.B == 90 or self.C == 90:
            return "Right"
        elif self.a == self.b == self.c:
            return "Equilateral"
        elif (self.A == self.B or self.A == self.C or self.C == self.B):
            return "Isosceles"
        else:
            return "Scalene"

    def __str__(self):
        return "a:%3.2f A:%3.2f deg\nb:%.2f B:%3.2f deg\nc:%3.2f C:%3.2f deg\n%s triangle" % (
            self.a, self.A, self.b, self.B, self.c, self.C, self.triangle_type)


if __name__ == '__main__':
    print(Triangle(*(float(x) for x in raw_input("Enter Sides (separated by a space): ").split())))
commented: Nice Massage :)) thanks! +4

Thanks bros for comments
specially pyTomy for introducing decorators and __str__ method.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.