2015-10-04 107 views
-6
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]] 
+0

幫助我們來幫助你。代碼打算做什麼?它在做什麼呢?我的建議:創建一個新問題,包括更好的解釋 – slezica

+0

它返回什麼? – ergonaut

+0

要理解代碼的作用,拿出一張紙,並記下所有變量的值。然後逐行通過代碼,添加新值。 – Barmar

回答

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中,你應該在你的變量和函數名稱(它的首選語法)中使用下劃線,我也會在你的變量名稱上工作..你希望它們非常具體,所以任何其他人都可以rstand它是什麼馬上。這是我將如何重命名變量。

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) 
+0

感謝您澄清我的疑問。 –

+0

@ bp_28肯定的事情,這有助於你理解它是如何工作的嗎?還可以看看我的最新編輯,並提供一些關於對象/變量名稱的建議 –