I recently saw Triangle exercise formulation and proposed solution and there are few things I am not sure about.
First, in the exercise instructions it says we should check that a <= b + c. I think it should be < instead of <= as you cannot make a triangle when one side is equal to the sum of the other two.
As for the proposed solution, there are few remarks that I would like to make. is_valid is implemented in the following way.
def is_valid(sides):
if not sides[0]:
return False
return all(side * 2 < sum(sides) for side in sides)
The condition not sides[0] will work only if sides are sorted; e.g. it won’t work for [1, 0, 0] . Also, none of the tests covers cases like this.
Here, sum(sides) is used in the generator. Is sum being evaluated in every iteration (making it quadratic complexity; here it is not important as sides has length 3, but I would prefer avoiding stuff like this in proposed solutions) or Python optimises this “under the hood”?
I believe it would be better idea to store sum(sides) in a variable and then use it in the generator.
Another thing I was not sure about is the proposed implementation of equilateral.
def equilateral(sides):
return is_valid(sides) and len(set(sides)) == 1
Does it really make sense to check if triangle is valid here? Isn’t it sufficient to check if all the sides have the same length greater than zero?
def equilateral(sides):
return len(set(sides)) == 1 and sides[0] > 0
Would you mind linking to which solution/code you’re referencing? Is this a specific community solution? Community solutions aren’t always perfect or optimal. Are you asking how the code works? If that person’s solution could be better?
Those are notes and not intended to be the “optimal” solution. The notes explicitly say this is a “reasonable” solution – not an optimized solution. You can suggest improvements to those notes via a PR to the linked file.