How to solve the triangle judgment problem in Python

This problem is a geometry challenge where we’re provided three lengths corresponding to the sides of a triangle. We need to determine whether we can create a triangle with these lengths. In this Answer, we’ll solve this problem using Python and a step-by-step code explanation.

Solution: Triangle judgment problem

In this problem, we have to implement the triangle inequality theorem. This theorem states that the sum of any two sides must exceed the value of the third side to be a valid triangle. This is illustrated in the diagram below:

Example of a valid triangle
Example of a valid triangle

From the diagram, we can deduce the following details:

  • 7+4=11>57 + 4 = 11 > 5

  • 7+5=12>47 + 5 = 12 > 4

  • 4+5=9>74 + 5 = 9 > 7

Hence, it’s a valid triangle. We can implement this condition in code form:

def trianglejudgment(first, second, third):
if first + second > third and first + third > second and second + third > first:
return True
else:
return False
first = 7
second = 4
third = 5
if trianglejudgment(first, second, third):
print("Valid")
else:
print("Not valid")

Code explanation

  • Line 1: The definition of our trianglejudgment function, which takes the three sides (first, second, and third) as parameters. 

  • Lines 2–3: We utilize conditional statements to check if the sum of any of the two sides is greater than the third side. If it is, we return True because that is the condition it needs to meet.

  • Lines 4–5: If it fails the check performed in the previous line, we return False because it won’t make a valid triangle.

  • Lines 11–14: Code to call and test the trianglejudgment function.

By solving the triangle inequality theorem, we don’t just delve into geometry but can apply this skill in real-life situations. This can be applied in construction measurements or scientific simulations, where confirming if a triangle is valid is a practical necessity.


Free Resources

Copyright ©2025 Educative, Inc. All rights reserved