2013-05-29 56 views
-4

我需要为这个问题使用elif吗?我该如何解决它? 对不起,这个超级noob问题。Python的布尔参数3

def hint1(p1, p2, p3, p4): 
    ''' (bool, bool, bool, bool) -> bool 
    Return True iff at least one of the boolen parameters 
    p1, p2, p3, or p4 is True. 
    >>> hint1(False, True, False, True) 
    True 
    ''' 
+1

'def hint1(* args):return any(args)' – abarnert

+0

严重的是,您提供了哪些学习资料?这是一个基本问题,你的学习资料应该包含你需要的答案。 – Marcin

回答

-2

你可以尝试

def hint1(p1,p2,p3,p4): 
    if p1 or p2 or p3 or p4: 
     return True 

或者

def hint1(p1,p2,p3,p4) 
    if p1: 
     return True 
    if p2: 
     return True 
    if p3: 
     return True 
    if p4: 
     return True 
    return False 
+1

或'返回p1或p2或p3或p4'。但“任何”都是正确的。 – Elazar

+0

谢谢!我还没有在课堂上学到任何功能,所以这是最有帮助的! – user2425814

1

关于尽可能短,你可以得到...

def hint1(p1,p2,p3,p4): 
    return any([p1,p2,p3,p4]) 
+1

'hint1 = lambda * x:any(x)'。较短:P – Elazar

0

any()方法接受一个可迭代和如果任何元素是t,则返回true后悔。

def hint1(p1, p2, p3, p4): 
    return any([p1, p2, p3, p4]) 
4
def hint1(*args): 
    return any(args) 

any函数采用一个可迭代,并返回True如果它的任何元素是真实的。

问题是,any需要一个可迭代的,而不是一堆单独的值。

这就是*args的用途。它将所有的参数都放在一个元组中,并将它们放入单个参数中。然后,您可以将该元组传递给any作为迭代器。有关更多详细信息,请参阅教程中的Arbitrary Argument Lists


由于埃拉扎尔指出,这并不整整4个参数的工作,它适用于任何参数的数目(甚至为0)。这是好还是坏取决于你的用例。

如果你想获得3个参数或5的错误,你当然可以添加一个明确的测试:

if len(args) != 4: 
    raise TypeError("The number of arguments thou shalt count is " 
        "four, no more, no less. Four shall be the " 
        "number thou shalt count, and the number of " 
        "the counting shall be four. Five shalt thou " 
        "not count, nor either count thou three, " 
        "excepting that thou then proceed to four. Six " 
        "is right out.") 

但实际上,这是更简单,只需使用一个静态的参数列表的话。

+0

+1,与原始问题有一点不同 - 它没有严格执行“4个参数”。 – Elazar

+2

@Elazar:但原来的问题没有在任何地方说明这一要求。 – abarnert

+0

+1 - 对于使用'* args' –