列表的Python幂集
我正在尝试实现一个函数来生成列表的powerset列表的Python幂集,python,powerset,Python,Powerset,我正在尝试实现一个函数来生成列表的powersetxs 一般的想法是,我们遍历xs的元素,并选择是否包含x。我面临的问题是,x的最终等于[None](一个None的单例列表),因为(我认为)s.add(x)返回None 这不是一个家庭作业,这是一个破解编码面试的练习 def powerSetBF(xs): powerSet = [] powerSet.append(set([])) for x in xs: powerSetCopy = powerSet
xs
一般的想法是,我们遍历xs
的元素,并选择是否包含x
。我面临的问题是,x的最终等于[None]
(一个None
的单例列表),因为(我认为)s.add(x)
返回None
这不是一个家庭作业,这是一个破解编码面试的练习
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
结果
set([(1, 2), (1, 3), (1, 2, 3, 4), (1,), (2,), (3,), (1, 4), (4,), (), (2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4), (1, 2, 3), (3, 4), (2, 4)])
itertools.compositions
的源代码可以在这里找到,其中有一些简洁的优化:
从以下位置查看动力集的示例:
对于给定列表长度范围内的整数,使所有整数都成为可能,并将它们作为一个对象组合在一起。这里有一个不使用任何模块的递归解决方案:
def pset(myset):
if not myset: # Empty list -> empty set
return [set()]
r = []
for y in myset:
sy = set((y,))
for x in pset(myset - sy):
if x not in r:
r.extend([x, x|sy])
return r
print(pset(set((1,2,3,4))))
#[set(), {1}, {2}, {1, 2}, {3}, {1, 3}, {2, 3}, {1, 2, 3}, {4},
# {1, 4}, {2, 4}, {1, 2, 4}, {3, 4}, {1, 3, 4}, {2, 3, 4}, {1, 2, 3, 4}]
你能提供更多的背景吗?示例输入和预期与实际输出的对比?捕获[s.add(x)的返回值在powerSetCopy中为s]
绝对错误。它将始终是一个None
s的列表s.add(x)
返回None
。可能related@user2993016此代码中有很多错误。e、 g.powerSet=powerSet.extend(带x)
将None
分配给powerSet
,因为extend
修改到位并返回None
。我建议学习更多关于python中列表操作的知识。请注意,文档中的代码与itertools的源代码“大致相当”。组合
,它是用C实现的,因此它比用纯Python代码实现效率更高。
from itertools import chain, combinations
def powerset(iterable):
"list(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))
def pset(myset):
if not myset: # Empty list -> empty set
return [set()]
r = []
for y in myset:
sy = set((y,))
for x in pset(myset - sy):
if x not in r:
r.extend([x, x|sy])
return r
print(pset(set((1,2,3,4))))
#[set(), {1}, {2}, {1, 2}, {3}, {1, 3}, {2, 3}, {1, 2, 3}, {4},
# {1, 4}, {2, 4}, {1, 2, 4}, {3, 4}, {1, 3, 4}, {2, 3, 4}, {1, 2, 3, 4}]