CMU Coding Bootcamp
at private/coded/push-mttnlwyrtnss 37 lines 1.4 kB view raw
1from math import sqrt 2 3 4def almostEqual(x: float, y: float) -> bool: 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 """Calculate the area of a triangle using Heron's formula.""" 15 semiperimeter = 0.5 * (a + b + c) 16 return sqrt( 17 semiperimeter * (semiperimeter - a) * (semiperimeter - b) * (semiperimeter - c) 18 ) 19 20 21def triangleAreaByCoordinates( 22 x1: float, y1: float, x2: float, y2: float, x3: float, y3: float 23) -> float: 24 """Calculate the area of a triangle given its coordinates.""" 25 A = distance((x1, y1), (x2, y2)) 26 B = distance((x2, y2), (x3, y3)) 27 C = distance((x3, y3), (x1, y1)) 28 return triangleArea(A, B, C) 29 30 31print("Testing triangleAreaByCoordinates()...", end="") 32assert almostEqual(triangleAreaByCoordinates(10, 11, 14, 11, 12, 13), 4) 33assert isinstance(triangleAreaByCoordinates(10, 11, 14, 11, 12, 13), float) 34assert almostEqual(triangleAreaByCoordinates(2, 4.0, 2, 7, 6.0, 7), 6) 35assert almostEqual(triangleAreaByCoordinates(0, 0, 12.0, 0, 12, 5), 30) 36assert almostEqual(triangleAreaByCoordinates(0, 0, 0, 1, 1, 1), 0.5) 37print("Passed!")