2016-06-25 2 views
-3
def two_of_three(a, b, c): 
"""Return x*x + y*y, where x and y are the two largest members of the 
positive numbers a, b, and 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 _____ 

함수 본문에 한 줄만 사용하면 어떻게 할 수 있습니까?Python에서 한 줄로 함수 정의하기

답변

1

거기에 아마 당신이 한 줄에 그것을해야하는 이유 유효한 이유는 없지만, 그것은 람다 수행 할 수 있습니다 :

def two_of_three(a,b,c): return sum(i*i for i in sorted((a,b,c))[-2:]) 

그런데 왜 : 한 줄에

>>> two_of_three = lambda a, b, c: sum(i*i for i in sorted((a,b,c))[-2:]) 

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

또는 def 사용 읽을 수있는 방식으로하지 않습니까?

def two_of_three(a,b,c): 
    """Return x*x + y*y, where x and y are the two largest members of the positive numbers a, b, and c""" 
    return sum(i*i for i in sorted((a,b,c))[-2:]) 
+0

명명 람다 자신의 의도 된 목적에 위배됩니다. PEP 8에서는 명시 적으로'def'가 명명 된 람다가 아닌 * 사용되어야한다고 언급되어 있습니다. – zondo

+0

@ zondo : 지적 해 주셔서 감사합니다. – mhawke

0

이것은 당신이 이제까지 할 일이 아니다, 그러나 이것은 작동합니다

def two_of_three(a, b, c): 
    return sum(x**2 for x in sorted([a, b, c])[1:])