# Defines two classes, Point() and Triangle().
# An object for the second class is created by passing named arguments,
# point_1, point_2 and point_3, to its constructor.
# Such an object can be modified by changing one point, two or three points
# thanks to the function change_point_or_points().
# At any stage, the object maintains correct values
# for perimeter and area.
#
# Written by Eric Martin for COMP9021

from math import sqrt

class Point():
    def __init__(self, x = None, y = None):
        if x == None and y == None:
            self.x = 0
            self.y = 0
        elif x == None or y == None:
            print('Need two coordinates, point not created.')
        else:
            self.x = x
            self.y = y

    def collinear(self, p2, p3):
        if (p2.y - self.y) * (p3.x - p2.x) ==\
                                   (p3.y - p2.y) * (p2.x - self.x):
            return True
        return False

class Triangle:
    def __init__(self, *, point_1, point_2, point_3):
        if point_1.collinear(point_2, point_3):
            self.error_message('Initialisation')
        else:
            self._initialise(point_1, point_2, point_3)

    def error_message(self, phase):
        if phase == 'Initialisation':
            print('Incorrect input, triangle not created.')
        else:
            print('Incorrect input, triangle not motified.')
       
    def change_point_or_points(self, *, point_1 = None,
                                        point_2 = None,
                                        point_3 = None):
        if not self._change_point_or_points(point_1, point_2, point_3):
            print('Could not perform this change.')
            return

    def _initialise(self, p1, p2, p3):
        self.p1 = p1
        self.p2 = p2
        self.p3 = p3
        length_12 = self._side_length(p1, p2)
        length_13 = self._side_length(p1, p3)
        length_23 = self._side_length(p2, p3)
        self.perimeter = length_12 + length_13 + length_23
        half_perimeter = self.perimeter / 2
        self.area = sqrt(half_perimeter *
                         (half_perimeter - length_12) *
                         (half_perimeter - length_13) *
                         (half_perimeter - length_23))


    def _change_point_or_points(self, p1, p2, p3):
        if not p1:
            p1 = self.p1
        if not p2:
            p2 = self.p2
        if not p3:
            p3 = self.p3
        if p1.collinear(p2, p3):
            self.error_message('Update')
            return False
        else:           
            self._initialise(p1, p2, p3)
        return True


    def _side_length(self, p, q):
        return sqrt((q.x - p.x) ** 2 + (q.y - p.y) ** 2)
        
        

            
            

Resource created Thursday 17 September 2015, 12:18:54 AM.

file: quiz_6_sol.py


Back to top

COMP9021 15s2 (Principles of Programming) is powered by WebCMS3
CRICOS Provider No. 00098G