This Python 3 based function returns if a triangle is or isn't right-angled given side lengths x, y, and z. I'm having an issue simplifying the conditional statement. Should this function check for acute, right, obtuse, scalene, isosceles, and equilateral angles, or are there conditions I can skip? Any feedback is appreciated.
def right_angled[x, y, z]:
"""This function returns if a triangle is or isn't
right-angled given side lengths x, y, and z."""
p = x + y + z #triangle perimeter
a_sym = p / 180 #triangle perimeter divided by 180
one = x * a_sym #angle one
two = y * a_sym #angle two
three = z * a_sym #angle three
if one and two or one and three or two and three == 90:
return "The triangle is right-angled."
elif one and two and three == 180:
return "The triangle is right-angled." #next conditional[s]?
else:
return "The triangle is not right-angled."
print[right_angled[4, 5, 6]]
jradich2234
1,4005 gold badges24 silver badges29 bronze badges
asked May 16, 2019 at 1:08
Your function is completely wrong.
You cannot find angle as ratio of a side and perimeter.
Expression if one and two
does not calculate sum - and
here is logical [boolean] operator.
To find whether rectangle is right, you can exploit Pythagorean theorem
def right_angled[a, b, c]:
if [a*a+b*b==c*c] or [c*c+b*b==a*a] or [a*a+c*c==b*b] :
return "The triangle is right-angled."
else:
return "The triangle is not right-angled."
Or just return boolean result
return [a*a+b*b==c*c] or [c*c+b*b==a*a] or [a*a+c*c==b*b]
answered May 16, 2019 at 2:31
MBoMBo
74k5 gold badges48 silver badges79 bronze badges
1
I suggest using the Pythagorean theorem to achieve this [a^2+b^2=c^2
] by testing the 3 combinations of side lengths. To compensate for floating point imprecision, compare within a range:
def right_angled[a, b, c, e]:
return abs[a*a+b*b-c*c]= b] and [a >= c]:
largest_triangle_side = a
elif [b >= c] and [b >= a]:
largest_triangle_side = b
else:
largest_triangle_side = c
# Applying Pythagorean theorem to check if triangle is Right Angled
# If a is largest side of triangle
if [largest_triangle_side == a]:
if [b**2 + c**2 == a**2]:
print["Triangle is Right Angled"]
else:
print["Triangle is Not Right Angled"]
# If b is largest side of triangle
if[largest_triangle_side == b]:
if[c**2 + a**2 == b**2]:
print["Triangle is Right Angled"]
else:
print["Triangle is Not Right Angled"]
# If c is largest side of triangle
if[largest_triangle_side == c]:
if[a**2 + b**2 == c**2]:
print["Triangle is Right Angled"]
else:
print["Triangle is Not Right Angled"]
Output of Above Code
Enter first side of triangle => 1
Enter second side of triangle => 2
Enter third side of triangle => 3
Triangle is Not Right Angled