Triangle Judgement Problem
Description
LeetCode Problem 610.
A pupil Tim gets homework to identify whether three line segments could possibly form a triangle.
However, this assignment is very heavy because there are hundreds of records to calculate.
Could you help Tim by writing a query to judge whether these three sides can form a triangle, assuming table triangle holds the length of the three sides x, y and z.
| x | y | z |
|----|----|----|
| 13 | 15 | 30 |
| 10 | 20 | 15 |
For the sample data above, your query should return the follow result:
| x | y | z | triangle |
|----|----|----|----------|
| 13 | 15 | 30 | No |
| 10 | 20 | 15 | Yes |
Solution
Approach: Triangle Inequality with CASE
Three lengths form a triangle exactly when each pair of sides is longer than the third side together:
x + y > zx + z > yy + z > x
All three must hold, so we combine them with AND inside a CASE and output 'Yes' or 'No' for each row, next to the original x, y and z.
The comparison must be strict. When two sides add up to exactly the third, like 5, 5 and 10, the three segments lie flat on one line and do not form a triangle, so that row is 'No'.
The Pandas version builds the same three-part condition as a boolean Series and uses np.where to turn it into 'Yes' / 'No'.
SELECT x,
y,
z,
CASE
WHEN x + y > z AND x + z > y AND y + z > x THEN 'Yes'
ELSE 'No'
END AS triangle
FROM triangle;