简体   繁体   English

如何从递归函数返回单个布尔值?

[英]How can I return a single boolean value from a recursive function?

I have this function:我有这个功能:

def most(P, S):
    def recursion(P,S):
        if len(S) == 0:
           return []
        elif P(S[0]):
            return [P(S[0])] + recursion(P, S[1:])
        else:
            return recursion(P, S[1:])
    if len(recursion(P,S)) > len(S)/2:
        return True
    else:
        return False

It takes an input of function, P and list, S. If the result of P(S[i]) is true for most of S, then the function most() should return true.它接受函数 P 和列表 S 的输入。如果 P(S[i]) 的结果对于大部分 S 为真,则函数 most() 应该返回真。 Any idea how I can do this recursively without a function inside of a function?知道如何在没有函数内部的函数的情况下递归地执行此操作吗? In other words, how can I return a single boolean value from a recursive function that takes a list as its input?换句话说,如何从将列表作为输入的递归函数返回单个布尔值?

Thanks!谢谢!

The biggest key to recursion is understanding the "terminal condition."递归的最大关键是理解“终止条件”。 What is the state where the function must stop?函数必须停止的状态是什么? In this case, it's the empty list.在这种情况下,它是空列表。

def most(pred, lst):
    if lst == []:
       return # but what do we return?

You will need to keep track of the number of list elements that meet an expectation... so you have to keep track of both the expectation (ie how many have to be true in order for "most" to be true), as well as the count so far.您将需要跟踪满足期望的列表元素的数量……因此您必须同时跟踪期望(即,为了使“大多数”为真,必须有多少为真),以及作为计数到目前为止。 Let's add those...让我们添加那些...

def most(pred, lst, threshold=None, count=0):
    if threshold is None:
        threshold = len(lst) // 2

    if lst == []:
        return count > threshold

So, then we need to "deconstruct" the list so that we can recurse over it.所以,然后我们需要“解构”列表,以便我们可以递归它。 Let's add that...让我们补充一下...

def most(pred, lst, threshold=None, count=0):
    if threshold is None:
        threshold = len(lst) // 2

    if lst == []:
        return count > threshold

    # Check the 'truth' of the head of the list...
    if pred(lst[0]):
        count += 1

    # ...and pass the tail of the list into the next iteration.
    return most(pred, lst[1:], threshold, count)

That should be all that you need.这应该就是你所需要的。 Now, I'll caution you that if your lists are of significant length, Python will blow its stack.现在,我要提醒您的是,如果您的列表很长,Python 会炸毁它的堆栈。 This is also significantly slower than a solution using a for loop or reduce , because of all the additional function calls.由于所有额外的函数调用,这也比使用for循环或reduce的解决方案慢得多。

If I were implementing most for production code, I would do this:如果我为生产代码实现most ,我会这样做:

def most(pred, lst):
    return sum(1 for x in lst if pred(x)) > len(lst) // 2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM