簡體   English   中英

如何從遞歸函數返回單個布爾值?

[英]How can I return a single boolean value from a recursive 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

它接受函數 P 和列表 S 的輸入。如果 P(S[i]) 的結果對於大部分 S 為真,則函數 most() 應該返回真。 知道如何在沒有函數內部的函數的情況下遞歸地執行此操作嗎? 換句話說,如何從將列表作為輸入的遞歸函數返回單個布爾值?

謝謝!

遞歸的最大關鍵是理解“終止條件”。 函數必須停止的狀態是什么? 在這種情況下,它是空列表。

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

您將需要跟蹤滿足期望的列表元素的數量……因此您必須同時跟蹤期望(即,為了使“大多數”為真,必須有多少為真),以及作為計數到目前為止。 讓我們添加那些...

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

    if lst == []:
        return count > threshold

所以,然后我們需要“解構”列表,以便我們可以遞歸它。 讓我們補充一下...

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)

這應該就是你所需要的。 現在,我要提醒您的是,如果您的列表很長,Python 會炸毀它的堆棧。 由於所有額外的函數調用,這也比使用for循環或reduce的解決方案慢得多。

如果我為生產代碼實現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