2016-10-02 25 views
2

我是新手編程,這是我第一次問一個問題,所以如果我打破任何協議,提前道歉。我在發帖之前試着尋找答案,但沒有找到任何匹配的結果。>在python 3返回==三角形練習

我正在通過思考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個答案時一起加入,即(1,1,2),則程序返回是,其中所述長度的2等於三分之一。但是2不大於2.我甚至增加了一系列'和'聲明,要求任何雙方的總和不能等於第三,並且它仍然返回是:

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

作者提到,第三個是「退化的三角形」,可能預示着這一結果。但爲什麼? 「>」和「> =」運算符是否提供了不同的功能?我錯過了什麼嗎?我如何限制操作員排除退化三角形?

+0

看起來像你的條件是錯誤的。 'c'必須小於或等於*'a + b'而不是三角形。 – Li357

回答

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

感謝您的豐富信息!你也回答了我的下兩個問題。至於在函數內部有輸入,練習特別要求我們編寫一個函數來獲取輸入,將它們轉換爲整數,然後應用is_triangle函數,所以我將它全部整合在一起,但我看到您滿足這些條件同時也保持獨立。謝謝你的提示! – whitehorse

+0

歡迎您@whitehorse!你能接受答案嗎? :d – jorgemdnt

0

您的情況明確指出,只有當一個長度嚴格大於另外兩個長度的總和時,線條長度纔會形成三角形。這不是你要找的條件。如果其中一個更大,您要取消輸入資格或等於其他兩個的總和。

這會工作:

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

啊,當然,我現在看到它!我在混合條件。我總是發現不是那麼混亂的邏輯。謝謝! – whitehorse