社区编辑:原来的标题是"python条件“,OP在问下面的代码有什么问题
我做了一个函数,用来确定三个边理论上是否可以形成一个三角形。在我看来,它工作得很好,但是当我在pyschools.com网站中输入代码时,它告诉我在某些测试用例中它不工作(不幸的是,它没有向我展示它没有工作的情况)。是不是我的代码中缺少了什么,那么在某些特殊情况下,我的逻辑会下降吗?非常感谢你的帮助。以下是功能:
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
发布于 2012-04-01 08:43:47
更容易做到的是:
def isTriangle(sides):
smallest,medium,biggest = sorted(sides)
return smallest+medium>=biggest and all(s>0 for s in sides)
(编辑:我决定说2,2,4
在技术上是一个三角形,但它是一个退化的三角形;如果您不认为它是三角形,则将>=
改为>
。)
这正是你要做的。您正在正确计算c = largest = max(x,y,z)
,但随后执行return math.sqrt(x**2+y**2)
检查它是否为直角三角形。
演示:
>>> isTriangle([2,2,6])
False
>>> isTriangle((5,5,9))
True
>>> isTriangle([-1,2,2])
False
下面我将提到如何简化您的代码:
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
在几乎任何现代编程语言中,“如果bool返回True in返回False”与“返回bool”是相同的。前者不必要地冗长,不应使用。
https://stackoverflow.com/questions/9966173
复制