列表的Python Power Set

use*_*016 3 python powerset

我正在尝试实现一个函数来生成列表的powerset 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
Run Code Online (Sandbox Code Playgroud)

pyl*_*ang 6

看看食谱中的powerset例子:itertools

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))
Run Code Online (Sandbox Code Playgroud)

对于一个range长度达到给定列表长度的整数,使所有可能combinationschain它们一起作为一个对象.


Ore*_*ail 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])
Run Code Online (Sandbox Code Playgroud)

结果

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)])
Run Code Online (Sandbox Code Playgroud)

可以在这里找到源代码itertools.combinations,其中有一些巧妙的优化:

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