Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Check whether triangle is valid or not if sides are given in Python
To check if three sides can form a valid triangle, we use the triangle inequality theorem. This states that the sum of any two sides must be greater than the third side for all three combinations.
For three sides a, b, and c, a triangle is valid if:
- a + b > c
- a + c > b
- b + c > a
However, we can simplify this by sorting the sides first. If the sum of the two smaller sides is greater than the largest side, then all conditions are automatically satisfied.
Algorithm
To solve this, we will follow these steps ?
- Sort the list of sides
- If sum of first two sides ? third side, then return False
- Otherwise, return True
Example
Let's implement the triangle validation function ?
def solve(sides):
sides.sort()
if sides[0] + sides[1] <= sides[2]:
return False
return True
sides = [14, 20, 10]
print(f"Sides {sides}: {solve(sides)}")
The output of the above code is ?
Sides [14, 20, 10]: True
Testing Different Cases
Let's test with multiple examples to understand better ?
def is_valid_triangle(sides):
sides.sort()
return sides[0] + sides[1] > sides[2]
# Test cases
test_cases = [
[14, 20, 10], # Valid triangle
[1, 2, 3], # Invalid: 1 + 2 = 3 (not greater than 3)
[5, 12, 13], # Valid triangle
[1, 1, 3], # Invalid: 1 + 1 < 3
[3, 4, 5] # Valid triangle (right triangle)
]
for sides in test_cases:
result = is_valid_triangle(sides.copy()) # copy to preserve original
print(f"Sides {sides}: {'Valid' if result else 'Invalid'}")
The output of the above code is ?
Sides [14, 20, 10]: Valid Sides [1, 2, 3]: Invalid Sides [5, 12, 13]: Valid Sides [1, 1, 3]: Invalid Sides [3, 4, 5]: Valid
Why This Method Works
After sorting, if a ? b ? c, we only need to check a + b > c because:
-
a + c > bis automatically true (since c ? b) -
b + c > ais automatically true (since both b and c are ? a)
Conclusion
Use the triangle inequality theorem to validate triangles. Sort the sides first, then check if the sum of the two smaller sides exceeds the largest side. This approach simplifies the validation from three checks to just one.
