whitehorse - 1 year ago 68

Python Question

I'm new to programming and this is my first time asking a question, so apologies in advance if I'm breaking any protocols. I tried searching for an answer before posting, but I didn't find any matching results.

I'm working my way through Think Python 2, and here is my solution to exercise 5.3, the triangle exercise.

`def is_tri():`

print('Give me 3 lengths')

a = int(input('first?\n'))

b = int(input('second?\n'))

c = int(input('third?\n'))

if a > b + c or b > a + c or c > a + b:

print('Not a triangle')

else:

print("Yes, it's a triangle")

is_tri()

What I noticed is that if I give 3 answers wherein 2 of the lengths equal the third when added together, i.e. (1,1,2), the program returns Yes. But 2 is not greater than 2. I even added a series of 'and' statements requiring that the sum of any two sides must not equal the third, and it still returns Yes:

if (a > b + c or b > a + c or c > a + b) and (a != b + c and b != a + c and c != a + b):

The author mentions that the sum of two sides equaling the third is a 'degenerate triangle', perhaps anticipating this outcome. But why? Don't the '>' and '>=' operators provide different functions? Am I missing something? How can I constrain the operator to exclude degenerate triangles?

Answer Source

If you need to declare that triangles that have the largest side equal to the sum of the others are invalid you are using the wrong operator, you should use `==`

in conjunction to `>`

, so your condition would look like:

```
if (a > b + c and a == b + c) or (b > a + c and b == a + c ) or (c > a + b and c == a + b):
```

Which is exactly the same as to making it like this:

```
if a >= b + c or b >= a + c or c >= a + b:
```

One nice way of doing it is sorting the list to get the largest element and then comparing to the sum of the others using slices, for this you would need the inputs to be in a list:

```
triangle_sides = [int(input('first?\n')), int(input('second?\n')), int(input('third?\n'))]
triangle_sides = sorted(triangle_sides, reverse=True)
if triangle_sides[0] >= sum(triangle_sides[1:]):
print("Absolutelly not a triangle")
else:
print("Congratulations, its a triangle")
```

I would also recommend you to get your inputs from outside the function, separating the "user interface" from the logic, your script would look like:

```
def is_valid_triangle(triangle_sides):
triangle_sides = sorted(triangle_sides, reverse=True)
if triangle_sides[0] >= sum(triangle_sides[1:]):
return False
return True
def triangle_validator():
print('Give me 3 lengths')
triangle_sides = [
int(input('first?\n')),
int(input('second?\n')),
int(input('third?\n'))
]
if is_valid_triangle(triangle_sides):
print('Yes, it\'s a triangle')
else:
print('Not a triangle')
if __name__ == '__main__':
triangle_validator()
```