列表的Python Power Set [英] Python Power Set of a List
问题描述
我正在尝试实现生成列表xs
的幂集的功能.
I am trying to implement a function to generate the powerset of a list xs
.
通常的想法是,我们遍历xs
的元素并选择是否包含x
.我面临的问题是withX
最终等于[None]
(带有None
的单例列表),因为(我认为)s.add(x)
返回None
.
The general idea is that we walk through the elements of xs
and choose whether to include x
or not. The problem I'm facing is that withX
ends up being equal to [None]
(a singleton list with None
) because (I think) s.add(x)
returns None
.
这不是家庭作业,而是破解编码面试"中的一项练习.
This isn't a homework assignment, it's an exercise in Cracking the Coding Interview.
def powerSetBF(xs):
powerSet = []
powerSet.append(set([]))
for x in xs:
powerSetCopy = powerSet[:]
withX = [s.add(x) for s in powerSetCopy] # add x to the list of sets
powerSet = powerSet.extend(withX) # append those entries
return powerSet
推荐答案
看看
对于整数的 For a 这篇关于列表的Python Power Set的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!range
给定列表的长度,使所有可能的 combinations
和 chain
一起作为一个对象.range
of integers up to the length of the given list, make all possible combinations
and chain
them together as one object.