Skip to content
Advertisement

Is there a faster way to know if it’s a real triangle?

The following code is intended to return 0 if it’s not possible to form a triangle with three given sides and return 1 if it is possible. Taking into account that it’s not possible for a triangle to have an area of zero or less, first I calculated the semiperimeter of this hypothetical triangle and then return 1 if the result is greater than the greatest value in the given list. I did the previous because if the semiperimeter is less than the greatest value in the list, then when calculating the area with the Heron formula it would be an undefined root.

def isTriangle(aList):
    semiperimeter = (aList[0] + aList[1] + aList[2]) / 2
    if semiperimeter > max(aList):
        return 1
    else:
        return 0

So I want to know if there is a faster way in Python to perform this (or at least with fewer lines of code).

Advertisement

Answer

You can check if the sum of the two smaller sides is at least as large as the longest side:

def check(aList)
    return sum(aList) - max(aList) > max(aList)

With python 3.8+, you can avoid recomputing the maximum twice using a walrus operator:

def check(aList):
    return (m := max(aList)) < sum(aList) - m

Both solutions rely on numerical comparisons returning a big boolean. In python bool is a subclass of int that has only two possible singleton values: True == 1 and False == 0. It’s standard to return a bool rather than 0 or 1 for something like this. In fact, your original conditional could be replaced by

return semiperimeter > max(aList)

Or, absorbing the previous line into the return:

return sum(aList) / 2 > max(aList)

You could also write

return sum(aList) > 2 * max(aList)

This version avoids any type conversions, regardless if whether you pass in floats or integers (/ 2 always results in a float).

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement