Problem 2: Is Triangle... Right? (100pts)
Problem
Write a function that takes three integers (maybe non-positive) and returns
True
if the three integers can form the three sides of a right triangle, otherwise returnsFalse
.
编写一个函数,接受三个整数(可能包含非正数),如果这三个整数能构成直角三角形的三条边,则返回 True
,否则返回 False
。
def is_right_triangle(a, b, c):
"""Given three integers (maybe non-positive), judge whether the three
integers can form the three sides of a right triangle.
>>> is_right_triangle(2, 1, 3)
False
>>> is_right_triangle(5, -3, 4)
False
>>> is_right_triangle(5, 3, 4)
True
"""
"*** YOUR CODE HERE ***"
Hints
Hint1: A right triangle (in Euclidean space) is a triangle that has exactly one angle equal to 90 degrees.
Hint2: The three sides of a triangle cannot be negative or zero.
Hint3: If you are not familiar with right triangles, please refer to this page.
-
直角三角形(在欧几里得空间中)是指恰好有一个角等于 90 度的三角形。
-
三角形的三条边不能是负数或零。
-
如果您不熟悉直角三角形,请参考此页面。
-
right triangle
不是“正确的三角形”!!!别看错题了 -
直角三角形的斜边最长,可以用
max
函数获取斜边长
Solutions
直接判断
def is_right_triangle(a, b, c):
# 1. Sides must be positive
if a <= 0 or b <= 0 or c <= 0:
return False
# 2. Check the Pythagorean theorem
return (a**2 + b**2 == c**2 or
a**2 + c**2 == b**2 or
b**2 + c**2 == a**2)
用 max
函数获取斜边长
def is_right_triangle(a, b, c):
# 1. Sides must be positive
if a <= 0 or b <= 0 or c <= 0:
return False
# 2. Check the Pythagorean theorem
return (a**2 + b**2 + c**2 - 2 * max(a, b, c)**2) == 0