我在使用Python的powerset中陷入了递归

2024-09-27 22:33:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在写一个程序来返回一组数的子集。 例如:list = [1,2,3] {my函数将返回[[], [1], [2], [3]] 这是我的密码

# 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));

Tags: 函数程序密码lenreturnifmydef
2条回答

有一个内置的“subset”包

import itertools

def subset(x):
    all_list = []
    for i in range(len(x)+1):
        all_list+=list(itertools.combinations(x,i))
    return all_list

print subset([1,2,3])
[output>>>] [(), (1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3)]

问题是您对list对象进行了变异,因此最后一行中的两个powerSet将不会收到相同的列表(例如,在第一个调用中,第一个powerSet将得到[1,2],而第二个将得到[1])。在

解决方案是在传递list时复制它:

powerSet(list[:]) + [[temp] + x for x in powerSet(list[:])]

相关问题 更多 >

    热门问题