Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/354.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
列表的Python幂集_Python_Powerset - Fatal编程技术网

列表的Python幂集

列表的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

我正在尝试实现一个函数来生成列表的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}]