Python列表的幂集

4
我正在尝试实现一个函数来生成列表xs的幂集。一般的想法是我们遍历xs的元素并选择是否包含x。我面临的问题是withX最终等于[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

1
可以提供更多的上下文吗?例如输入、期望输出和实际输出的示例? - MSeifert
2
捕获[s.add(x) for s in powerSetCopy]的返回值肯定是错误的。它总是一个由None组成的列表。s.add(x)返回的是None - Paul Rooney
1
也许相关:打印字符串的幂集 - chickity china chinese chicken
1
@user2993016 这段代码中有相当多的错误。例如,powerSet = powerSet.extend(withX) 会将 None 赋值给 powerSet,因为 extend 是就地修改并返回 None。我建议您学习更多关于 Python 中列表操作的知识。 - Paul Rooney
3个回答

9

请看itertools recipes中的powerset示例:

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

对于给定列表长度的范围内的整数,生成所有可能的组合并将它们链接成一个对象。


3
以下是一个不使用任何模块的递归解决方案,供参考:

以下是一个不使用任何模块的递归解决方案:

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}]

2
import itertools

def powerset(L):
  pset = set()
  for n in xrange(len(L) + 1):
    for sset in itertools.combinations(L, n):
      pset.add(sset)
  return pset

powerset([1, 2, 3, 4])

结果

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.combinations的源代码可以在这里找到,其中有一些巧妙的优化:

https://docs.python.org/3/library/itertools.html#itertools.combinations


请注意,文档中的代码“大致等同于”itertools.combinations的源代码,该代码是用C实现的,因此比使用纯Python代码更有效率。 - PM 2Ring

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接