[英]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.