简体   繁体   English

递归 Python 函数返回项的 PowerSet

[英]Recursive Python function returning PowerSet of items

I'm trying to debug a program and am running into issues.我正在尝试调试程序并遇到问题。 Can anybody direct me to the issue here?任何人都可以指导我解决这里的问题吗?

The program is meant to take a list of items, and returns the list of powersets for those items.该程序旨在获取项目列表,并返回这些项目的 powerset 列表。

An example:一个例子:

>>> getAllSubsets([1,2])
[[1,2],[1],[2],[]]

The code:编码:

def getAllSubsets(lst):
    if not lst:
        return []
    withFirst = [ [lst[0]] + rest for rest in getAllSubsets(lst[1:]) ]
    withoutFirst = getAllSubsets(lst[1:])
    return withFirst + withoutFirst

There are better recipes, yes.有更好的食谱,是的。 But I think the problem with your code is that you should replace return [] with return [[]] .但我认为你的代码的问题是你应该用return [[]]替换return [] return [[]] The empty set is itself a subset.空集本身就是一个子集。

There's a powerset generator in the recipes section of the itertools documentation ; itertools 文档的 recipes 部分有一个powerset生成器; you should use that.你应该使用它。

def powerset(iterable):
    "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
    s = list(iterable)
    return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))

I found this solution on the internet:我在互联网上找到了这个解决方案:

def powset3(seq):
    if seq:
        p = powset3(seq[1:])
        return p + [x + seq[:1] for x in p]
    else:
        return [[]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM