Skip to main content
 首页 » 编程设计

python -> 在 python 3 三角形练习中返回 ==

2025年04月02日8zengkefu

我是编程新手,这是我第一次提出问题,如果我违反了任何协议(protocol),请提前致歉。我在发帖前尝试搜索答案,但没有找到任何匹配的结果。

我正在学习 Think Python 2,这是我对练习 5.3(三角形练习)的解决方案。

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() 

我注意到,如果我给出 3 个答案,其中 2 个长度加在一起等于第三个长度,即 (1,1,2),程序返回是。但是2不大于2,我什至加了一系列'and'语句,要求任意两条边之和不能等于第三条,结果还是返回Yes:

如果 (a > b + c 或 b > a + c 或 c > a + b) 和 (a != b + c and b != a + c and c != a + b):

作者提到两条边之和等于第三条边是“退化三角形”,也许是在预料到这一结果。但为什么? “>”和“>=”运算符不提供不同的功能吗?我错过了什么吗?如何约束算子排除退化三角形?

请您参考如下方法:

如果您需要声明最大边等于其他边之和的三角形是无效的,那么您使用了错误的运算符,您应该将 == 与 > 结合使用,所以你的情况看起来像:

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

这与像这样制作完全一样:

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

一个很好的方法是对列表进行排序以获得最大的元素,然后使用切片与其他元素的总和进行比较,为此您需要将输入放在列表中:

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") 

我还建议您从函数外部获取输入,将“用户界面”与逻辑分开,您的脚本如下所示:

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()