【问题标题】:Python Power Set of a List [duplicate]列表的Python幂集[重复]
【发布时间】:2017-05-28 08:09:01
【问题描述】:

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

【问题讨论】:

  • 您能提供更多上下文吗?示例输入和预期与实际输出?
  • 捕获[s.add(x) for s in powerSetCopy] 的返回值肯定是错误的。它始终是Nones 的列表。 s.add(x) 返回None
  • @user2993016 这段代码有不少错误。例如powerSet = powerSet.extend(withX) 会将None 分配给powerSet,因为extend 在原地修改并返回None。我建议学习更多关于 python 中的列表操作。

标签: python powerset


【解决方案1】:

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

对于不超过给定列表长度的整数range,将所有可能的combinationschain 一起作为一个对象。

【讨论】:

    【解决方案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 代码更高效。
    【解决方案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}]
    

    【讨论】:

      猜你喜欢
      • 2012-03-04
      • 2013-09-20
      • 1970-01-01
      • 1970-01-01
      • 2013-09-05
      • 1970-01-01
      • 2017-04-25
      • 2016-06-30
      相关资源
      最近更新 更多