【发布时间】:2021-01-12 10:14:59
【问题描述】:
我正在使用递归函数来查找所有列表的子集并制作它们的二维列表。这是我编码的方式:
我将一个列表和一个索引传递给我的函数,然后我选择是否保留该索引的项目。所以我用新列表中下一个项目的索引再调用该函数两次(一次不进行更改,一次删除项目)。每当我传递的索引与列表的长度相等时,我就达到了我想要制作的最终列表。
问题是最终列表没有附加到主列表!不知道能不能追加或者算法有问题或者...
这是它的样子:
ans = [] # The main list which subsets will be added to
def zir_maj(li,idx=0):
global ans
if len(li) == idx: # if it be true I have reached the end of tree
ans.append(li)
return None # by this I will end the function
zir_maj(li, idx + 1) # I choose to keep my item
li.pop(idx)
zir_maj(li, idx) # I choose to delete my item
return ans # I return it for print
print(zir_maj(['a','b','c']))
输出是:
[[], [], [], []]
【问题讨论】:
-
提示:一个函数可以修改它的参数,如果它是可变的。
标签: python algorithm recursion scope