-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtriangles.py
71 lines (55 loc) · 1.5 KB
/
triangles.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
"""Functions for working with triangles.
A triangle is represented by a tuple (a, b, c),
which defines the length of the three sides.
"""
import math
def valid(tri):
"""Check if a tuple represents a valid triangle.
Args:
tri (tuple): length of the three sides
Returns:
bool: True if valid, False otherwise
"""
# if not exactly three sides
if len(tri) != 3:
return False
a, b, c, = sorted(tri)
# if any side is not positive
if a <= 0:
return False
# longest side is not too long
return c < a + b
def area(tri):
"""Calculate the area using Heron's Formula.
Args:
tri (tuple): length of the three sides
Returns:
float: area of the triangle
Raises:
ValueError: If the triangle is invalid.
"""
if not valid(tri):
raise ValueError("invalid triangle")
# calculate half the perimeter
a, b, c, = tri
s = 0.5 * (a + b + c)
# calculate the triangle area
return math.sqrt(s * (s-a) * (s-b) * (s-c))
def classify(tri):
"""Determine the type of triangle.
Args:
tri (tuple): length of the three sides
Returns:
str: "Equilateral", "Isosceles", or "Scalene"
Raises:
ValueError: If the triangle is invalid.
"""
if not valid(tri):
raise ValueError("invalid triangle")
a, b, c = tri
if a == b == c:
return "Equilateral"
elif a == b or b == c or a == c:
return "Isosceles"
else:
return "Scalene"