我正在写一个程序来返回一组数的子集。
例如:list = [1,2,3]
{my函数将返回
# Write a powerSet function
def powerSet(list):
if len(list) == 0:
return [[]];
else:
temp = list.pop()
return powerSet(list) + [[temp] + x for x in powerSet(list)];
list = [1,2,3];
print(powerSet(list));
有一个内置的“subset”包
问题是您对
list
对象进行了变异,因此最后一行中的两个powerSet
将不会收到相同的列表(例如,在第一个调用中,第一个powerSet
将得到[1,2]
,而第二个将得到[1]
)。在解决方案是在传递
list
时复制它:相关问题 更多 >
编程相关推荐