简体   繁体   中英

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. 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. This is also significantly slower than a solution using a for loop or reduce , because of all the additional function calls.

If I were implementing most for production code, I would do this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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