请解释一下这段代码的工作原理?

时间:2015-10-04 03:14:21

标签: python

def gSubsets(L):
    if len(L) == 0:
        print '2'
        return [[]]
    smaller = gSubsets(L[:-1]) 
    extra = L[-1:]
    print L     
    new = []
    for small in smaller:
        new.append(small+extra)
    return smaller+new
print gSubsets([1,2])

我是python的初学者。我没有得到实际上return最后的结果并没有结束:

smaller + new =[[][5]]

1 个答案:

答案 0 :(得分:2)

将其分解成碎片

def gSubsets(L): #recursive function
    if len(L) == 0: #when weve reached the last subset we then have to handle an empty list
        print '2'
        return [[]] #returns a list of lists for the small in smaller
    smaller = gSubsets(L[:-1]) #get subsets by recursive call for all elements in the list except the last one
    extra = L[-1:] #get the last element in the list not used in this recursive call
    print L     
    new = []
    for small in smaller: #loop through list of lists from recursive call
        new.append(small+extra) #append all combinations of the last element in the list to every other element in the same list to new
    return smaller+new #return subset with new combinations

print gSubsets([1,2])

此输出

>>> 2
>>> [1]
>>> [1, 2]
>>> [[], [1], [2], [1, 2]]

顺便说一下,在python中你应该在你的变量和函数名中使用下划线(它是首选的语法),我也会在你的变量名上工作..你希望它们非常具体,所以其他任何人都可以理解什么是马上..这就是我将如何重命名变量。

def generate_subsets_from_list(input_list):
    if len(input_list) == 0:
        # print '2'  -- not sure why you are printing 2 here?
        return [[]]
    subsets = generate_subsets_from_list(input_list[:-1]) 
    last_element = L[-1:]
    print L     
    return_list = []
    for subset in subsets:
        return_list.append(subset+last_element)
    return subsets+return_list

initial_list = [1,2]
print generate_subsets_from_list(initial_list)