Reputation: 35
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).
Upvotes: 0
Views: 508
Reputation: 114468
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
).
Upvotes: 4
Reputation: 6728
To determine if given 3 sides can form a valid triangle, I would suggest using Triangle Inequality Theorem. It roughly states that the sum of any two sides must always be equal or greater than the other side to be able to form a valid triangle.
Therefore, I would instead write something along this line. [Edited: initialization according to Avinash]
def isTriangle(aList):
a,b,c = aList
return (a + b >= c and a + c >= b and b + c >= a)
In case you really want to make it return 0
or 1
instead of boolean
then you can use this return instead.
return 1 if a + b >= c and a + c >= b and b + c >= a else 0
Upvotes: -1
Reputation: 2438
You asked for shorter code. That one is possible to do as a oneliner.
def isTriangle(aList):
return ((aList[0] + aList[1] + aList[2]) / 2) > max(aList) and 1 or 0
Exatly the same code, but just written shorter
Upvotes: -1