CMU Coding Bootcamp
at private/coded/push-mttnlwyrtnss 52 lines 1.9 kB view raw
1from math import sqrt 2 3 4def almostEqual(x, y): 5 return abs(x - y) < 10**-9 6 7 8def distance(a: tuple[float, float], b: tuple[float, float]) -> float: 9 """Calculate the distance between two points using the Euclidean distance formula.""" 10 return sqrt((b[0] - a[0]) ** 2 + (b[1] - a[1]) ** 2) 11 12 13def triangleArea(a: float, b: float, c: float) -> float: 14 """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.""" 15 semiperimeter = 0.5 * (a + b + c) 16 return sqrt( 17 semiperimeter * (semiperimeter - a) * (semiperimeter - b) * (semiperimeter - c) 18 ) 19 20 21def intersect(m1: float, b1: float, m2: float, b2: float) -> tuple[float, float]: 22 """Calculate the intersection point of two lines.""" 23 x = (b2 - b1) / (m1 - m2) 24 y = m1 * x + b1 25 return x, y 26 27 28def areaWithinThreeLines( 29 m1: float, b1: float, m2: float, b2: float, m3: float, b3: float 30) -> float | None: 31 """Calculate the area of a triangle formed by three lines.""" 32 if m1 == m2 or m2 == m3 or m3 == m1: 33 return None 34 a = intersect(m1, b1, m2, b2) 35 b = intersect(m2, b2, m3, b3) 36 c = intersect(m3, b3, m1, b1) 37 return triangleArea(distance(a, b), distance(b, c), distance(c, a)) 38 39 40print("Testing areaWithinThreeLines()...", end="") 41assert almostEqual(areaWithinThreeLines(0, 7, 1, 0, -1, 2), 36) 42assert almostEqual(areaWithinThreeLines(1, -5, 0, -2, 2, 2), 25) 43assert almostEqual(areaWithinThreeLines(0, -9.75, -6, 2.25, 1, -4.75), 21) 44assert almostEqual(areaWithinThreeLines(1, -5, 0, -2, 2, 25), 272.25) 45assert almostEqual(areaWithinThreeLines(1, 2, 3, 4, 5, 6), 0) 46 47# The first two lines are parallel: 48assert areaWithinThreeLines(1, 2, 1, 4, 0, 7) == None 49 50# Here, the second and third lines are parallel 51assert areaWithinThreeLines(5, 2, 1, 4, 1, 6) == None 52print("Passed!")