from math import sqrt def almostEqual(x, y): return abs(x - y) < 10**-9 def distance(a: tuple[float, float], b: tuple[float, float]) -> float: """Calculate the distance between two points using the Euclidean distance formula.""" return sqrt((b[0] - a[0]) ** 2 + (b[1] - a[1]) ** 2) def triangleArea(a: float, b: float, c: float) -> float: """Use herons formula: `sp = (a+b+c)/2` & `sqrt(sp(sp-a)(sp-b)(sp-c))` to calculate the area of a triangle using it's side lengths.""" semiperimeter = 0.5 * (a + b + c) return sqrt( semiperimeter * (semiperimeter - a) * (semiperimeter - b) * (semiperimeter - c) ) def intersect(m1: float, b1: float, m2: float, b2: float) -> tuple[float, float]: """Calculate the intersection point of two lines.""" x = (b2 - b1) / (m1 - m2) y = m1 * x + b1 return x, y def areaWithinThreeLines( m1: float, b1: float, m2: float, b2: float, m3: float, b3: float ) -> float | None: """Calculate the area of a triangle formed by three lines.""" if m1 == m2 or m2 == m3 or m3 == m1: return None a = intersect(m1, b1, m2, b2) b = intersect(m2, b2, m3, b3) c = intersect(m3, b3, m1, b1) return triangleArea(distance(a, b), distance(b, c), distance(c, a)) print("Testing areaWithinThreeLines()...", end="") assert almostEqual(areaWithinThreeLines(0, 7, 1, 0, -1, 2), 36) assert almostEqual(areaWithinThreeLines(1, -5, 0, -2, 2, 2), 25) assert almostEqual(areaWithinThreeLines(0, -9.75, -6, 2.25, 1, -4.75), 21) assert almostEqual(areaWithinThreeLines(1, -5, 0, -2, 2, 25), 272.25) assert almostEqual(areaWithinThreeLines(1, 2, 3, 4, 5, 6), 0) # The first two lines are parallel: assert areaWithinThreeLines(1, 2, 1, 4, 0, 7) == None # Here, the second and third lines are parallel assert areaWithinThreeLines(5, 2, 1, 4, 1, 6) == None print("Passed!")