Lis的Python幂集

2024-05-29 11:49:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图实现一个函数来生成列表的powersetxs

一般的想法是,我们遍历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

Tags: 函数innoneadd元素列表for单例
3条回答
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

看看^{} 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))

对于一个长度不超过给定列表长度的^{}整数,使它们可以作为一个对象一起^{}^{}

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

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

相关问题 更多 >

    热门问题