递归函数如何返回列表元组?

时间:2014-11-10 04:07:45

标签: python recursion

问题是: 定义一个名为separate的递归函数;它传递一个谓词和一个列表;它返回一个2元组,其0索引是谓词返回True的参数列表中所有值的列表,其1索引是谓词返回False的参数列表中所有值的列表。致电separate(predicate.is_positive,[1,-3,-2,4,0,-1,8])会返回([1,4,8], [-3,-2,0,-1])。注0不是正数。提示:与笔记中的幂函数的快速版本一样,您可以定义和绑定(但不重新绑定)本地名称,或者可以编写嵌套函数(如方形函数)来帮助计算。

以下是他的权力函数的例子:

def power(a,n):
    def square(n) : n*n
    if n == 0:
        return 1
    else:
       if n%2 == 1:
           return a*power(a,n-1)
       else:
           return square( power(a,n//2) )

我的尝试:

def separate(p,l):
    l1=[]
    l2=[]
    if l == []:
        return [],[]
    else:
        if p(l[0]):
            l1=([l[0]]+map_pos(p,l[1:]))
            return l1,l2
        else:
            l2.extend([l[0]]+separate(p,l[1:]))
            return l1,l2

调用此函数: print(predicate.is_positive,[1, -3, -2, 4, 0, -1, 8])会给我: TypeError: can only concatenate list (not "tuple") to list

注意谓词.is_positive是谓词模块中的一个函数,它接受一个int,如果int为正则返回True。

有人可以帮我这个吗?实际的代码将非常值得赞赏。

1 个答案:

答案 0 :(得分:1)

这可能是你试图做的事情

def separate(p, L):
    if L == []:
        return [], []

    l1, l2 = separate(p, L[1:])

    item = L[0]

    if p(item):
        l1.append(item)
    else:
        l2.append(item)
    return l1, l2    

由于L[1:]为每个项目创建新列表,因此效率不高

您可以使用默认参数来避免制作切片

def separate(p, L, idx=0):
    if idx == len(L):
        return [], []

    l1, l2 = separate(p, L, idx + 1)

    item = L[idx]

    if p(item):
        l1.append(item)
    else:
        l2.append(item)
    return l1, l2    

它看起来仍然很笨拙。它并不是一个需要递归解决方案的任务