如何计算python中三个中最大两个数的平方和

时间:2014-04-04 05:51:48

标签: python

来自C / Java背景,我为下面的问题编写了python程序(如下所示),这个程序无法编译,因为,?:(三元运算符)在python中不可用。

Write a function that takes three positive numbers and returns the sum of the squares of the two largest numbers. Use only a single expression for the body of the function:

def two_of_three(a, b, c):
    """Return x*x + y*y, where x and y are the two largest of a, b, c.

    >>> two_of_three(1, 2, 3)
    13
    >>> two_of_three(5, 3, 1)
    34
    >>> two_of_three(10, 2, 8)
    164
    >>> two_of_three(5, 5, 5)
    50
    """
    return ((a>b)? 
                ((b>c)?(a*a+b*b):(a*a+c*c))
                :
                ((a>c)?(a*a+b*b):(c*c+b*b))
                )

我的问题:

请告诉我一种编写单个表达式的替代方法吗?

4 个答案:

答案 0 :(得分:6)

试试这个:

def two_of_three(a,b,c):
    return a**2+b**2+c**2-min([a,b,c])**2

答案 1 :(得分:0)

def two_of_three(a,b,c):
    return (a*a+b*b if a>c<b else
            c*c+a*a if c>b<a else
            b*b+c*c)

答案 2 :(得分:0)

def Largest_Square_Two(a, b, c):
    return max(a*a+b*b, b*b+c*c, c*c+a*a)

答案 3 :(得分:-1)

def two_of_three(a,b,c):
    num1 = max(a,b)
    num2 = max(b,c)
    if num1==num2:
        num1 = max(a,c)

    return num1**2 + num2**2