Python中的递归堆栈调用 - 映射

时间:2017-12-17 15:23:03

标签: python recursion

在处理递归函数以生成所有子集的集合时,我注意到下面定义的这个函数给了我一个意想不到的输出:

[[]], None, None, None and None.

为什么它"工作"当for循环处于活动状态时,它会正确显示,而当它不活动时,它完全不会映射到所需的子集。

print(ss) 

不打印与for循环处于活动状态时相同的事情。

我错过了什么?

def get_all_subsets(some_list):



  """Returns all subsets of size 0 - len(some_list) for some_list"""
    if len(some_list) == 0:
        # If the list is empty, return the empty list
        return [[]]
    subsets = []

    first_elt = some_list[0]
    rest_list = some_list[1:]

    ss =  get_all_subsets(rest_list)
    print(ss)

    #    for partial_subset in ss:
    #        subsets.append(partial_subset)
    #        next_element = partial_subset[:] + [first_elt]
    #        subsets.append(next_element)
    #    return subsets


 L = [1,2,3,4]

 print(get_all_subsets(L))

想要看到的是:

[[2,3,4],[3,4],[4],[]]

这是一个更有价值的代码:

def get_all_subsets(some_list):
    """Returns all subsets of size 0 - len(some_list) for some_list"""
    if len(some_list) == 0:
        # If the list is empty, return the empty list
        return [[]]
    subsets = []

    first_elt = some_list[0]
    rest_list = some_list[1:]

    ss =  get_all_subsets(rest_list)
    print(ss)

    for partial_subset in ss:
        print(partial_subset)
        #        subsets.append(partial_subset)
#        next_element = partial_subset[:] + [first_elt]
#        subsets.append(next_element)
    return subsets

1 个答案:

答案 0 :(得分:1)

它不起作用,因为如果列表非空(您只是print()),则不返回任何内容。如果你没有明确地返回任何内容,那么函数会隐式返回None

def get_all_subsets(some_list): 
    if len(some_list) == 1: # if len is 1 then the last element was added
                            # previously, just add the empty list
        return [[]]

    if len(some_list) > 1:  # add rest of list and recurse
        return [some_list[1:]] + get_all_subsets(some_list[1:]) 


L = [1,2,3,4]
print( get_all_subsets(L))

输出:

[[2, 3, 4], [3, 4], [4], []]