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

时间:2016-10-02 02:45:32

标签: python python-3.x

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

我正在通过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),程序返回Yes。但是2不大于2.我甚至添加了一系列'和'声明,要求任何双方的总和不得等于第三,并且它仍然返回是:

if(a> b + c或b> a + c或c> a + b)和(a!= b + c和b!= a + c和c!= a + b):

提交人提到,双方等于第三方的总和是“退化三角形”,也许是预期这一结果。但为什么?不要'>'和'> ='运算符提供不同的功能?我错过了什么吗?如何约束运算符以排除退化三角形?

2 个答案:

答案 0 :(得分:1)

如果你需要声明最大边等于其他边的总和的三角形无效你使用了错误的算子,你应该==>结合使用,所以你的条件看起来像:

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

答案 1 :(得分:0)

您的情况明确指出,只有当一个长度严格大于另外两个长度的总和时,线长才会形成三角形。那不是你要找的条件。如果一个大于或等于其他两个的总和,您想取消输入的资格。

这样可行:

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