三角形不等式作为python条件的逻辑?
[社区编辑:最初的标题是“python条件”,OP询问下面的代码有什么问题] 我做了一个函数,用来确定三条边理论上是否可以形成一个三角形。在我看来,它工作得很好,但是当我在pyschools.com网站上输入代码时,它告诉我在一些测试用例中它不工作(不幸的是,它没有向我显示它不工作的用例)。我的代码中缺少一些东西,所以在某些特殊情况下,我的逻辑失败了?非常感谢你的帮助。 下面是函数:三角形不等式作为python条件的逻辑?,python,Python,[社区编辑:最初的标题是“python条件”,OP询问下面的代码有什么问题] 我做了一个函数,用来确定三条边理论上是否可以形成一个三角形。在我看来,它工作得很好,但是当我在pyschools.com网站上输入代码时,它告诉我在一些测试用例中它不工作(不幸的是,它没有向我显示它不工作的用例)。我的代码中缺少一些东西,所以在某些特殊情况下,我的逻辑失败了?非常感谢你的帮助。 下面是函数: import math def isTriangle(x, y, z): if x > 0 and
import math
def isTriangle(x, y, z):
if x > 0 and y > 0 and z > 0:
if x > y and x > z:
c = x
elif y > x and y > z:
c = y
else:
c = z
if c == math.sqrt(x**2 + y**2):
return True
else:
return False
else:
return False
这样做更容易:
def isTriangle(sides):
smallest,medium,biggest = sorted(sides)
return smallest+medium>=biggest and all(s>0 for s in sides)
< > >(编辑:我决定说<代码> 2,2,4/代码>在技术上是一个三角形,但是是一个退化的三角形;改变<代码> > <代码> > <代码> >代码>如果你不认为它是一个三角形的话)
这正是你正在做的。您正在正确计算c=max=max(x,y,z)
,但随后执行return math.sqrt(x**2+y**2)
,检查它是否为直角三角形
演示:
下面我将介绍如何简化您的代码:
import math # from math import * for such common functions
def isTriangle(x, y, z): # better to pass in a tuple or object, but this works
if x>0 and y>0 and z>0: # (then you could do all(s>0 for s in sides))
# (you could also do isTriangle(*sides))
# (you might need to add checks len(sides)==3
# if your input data might include e.g. squares)
if x > y and x > z: # \
c = x # |
elif y > x and y > z: # > This is the same as c = max(x,y,z)
c = y # |
else: # |
c = z # /
if c == math.sqrt(x**2 + y**2): # \
return True # | Same as return c==sqrt(x**2+y**2)
else: # |
return False # /
else:
return False
“if bool return True else return False”在几乎任何现代编程语言中都与“return bool”相同。前者是不必要的冗长,不应该使用。我很抱歉,我刚刚意识到我使x或y等于c,然后我测试了x或y==math.sqrt(x2+y2),这是错误的。我不知道如何删除我的帖子。再一次,我很抱歉。你不需要删除你的帖子,而是把它保留下来。这样,和你有同样问题的人就可以找到这个答案,而不是再问同样的问题。这是生命的循环!应该是
最小+中等>最大
<代码>最小+中等==最大是一条线。这将是一个共线/退化三角形,并且是故意做的。谢谢你为那些没有注意到的人指出这一点。
import math # from math import * for such common functions
def isTriangle(x, y, z): # better to pass in a tuple or object, but this works
if x>0 and y>0 and z>0: # (then you could do all(s>0 for s in sides))
# (you could also do isTriangle(*sides))
# (you might need to add checks len(sides)==3
# if your input data might include e.g. squares)
if x > y and x > z: # \
c = x # |
elif y > x and y > z: # > This is the same as c = max(x,y,z)
c = y # |
else: # |
c = z # /
if c == math.sqrt(x**2 + y**2): # \
return True # | Same as return c==sqrt(x**2+y**2)
else: # |
return False # /
else:
return False