Coverage for triangles.py: 68%
28 statements
« prev ^ index » next coverage.py v7.6.1, created at 2024-10-30 05:17 -0400
« prev ^ index » next coverage.py v7.6.1, created at 2024-10-30 05:17 -0400
1"""Functions for working with triangles.
3A triangle is represented by a tuple (a, b, c),
4which defines the length of the three sides.
5"""
7import math
10def valid(tri):
11 """Check if a tuple represents a valid triangle.
13 Args:
14 tri (tuple): length of the three sides
16 Returns:
17 bool: True if valid, False otherwise
18 """
19 # if not exactly three sides
20 if len(tri) != 3:
21 return False
22 a, b, c, = sorted(tri)
23 # if any side is not positive
24 if a <= 0:
25 return False
26 # longest side is not too long
27 return c < a + b
30def area(tri):
31 """Calculate the area using Heron's Formula.
33 Args:
34 tri (tuple): length of the three sides
36 Returns:
37 float: area of the triangle
38 """
39 if not valid(tri):
40 raise ValueError("invalid triangle")
41 # calculate half the perimeter
42 a, b, c, = tri
43 s = 0.5 * (a + b + c)
44 # calculate the triangle area
45 return math.sqrt(s * (s-a) * (s-b) * (s-c))
48def classify(tri):
49 """Determine the type of triangle.
51 Args:
52 tri (tuple): length of the three sides
54 Returns:
55 str: "Equilateral", "Isosceles", or "Scalene"
56 """
57 if not valid(tri):
58 raise ValueError("invalid triangle")
59 a, b, c = tri
60 if a == b == c:
61 return "Equilateral"
62 elif a == b or b == c or a == c:
63 return "Isosceles"
64 else:
65 return "Scalene"
68if __name__ == "__main__":
69 t = (3, 4, 5)
70 print(f"valid({t}):", valid(t))
71 print(f"area({t}):", area(t))
72 print(f"classify({t}):", classify(t))