把它分解成塊
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)
幫助我們來幫助你。代碼打算做什麼?它在做什麼呢?我的建議:創建一個新問題,包括更好的解釋 – slezica
它返回什麼? – ergonaut
要理解代碼的作用,拿出一張紙,並記下所有變量的值。然後逐行通過代碼,添加新值。 – Barmar