列表的Python Power Set [英] Python Power Set of a List

查看:106
本文介绍了列表的Python Power Set的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试实现生成列表xs的幂集的功能.

I am trying to implement a function to generate the powerset of a list xs.

通常的想法是,我们遍历xs的元素并选择是否包含x.我面临的问题是withX最终等于[None](带有None的单例列表),因为(我认为)s.add(x)返回None.

The general idea is that we walk through the elements of xs and choose whether to include x or not. The problem I'm facing is that withX ends up being equal to [None] (a singleton list with None) because (I think) s.add(x) returns None.

这不是家庭作业,而是破解编码面试"中的一项练习.

This isn't a homework assignment, it's an exercise in Cracking the Coding Interview.

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

推荐答案

看看

对于整数的 range 给定列表的长度,使所有可能的 combinations chain 一起作为一个对象.

For a range of integers up to the length of the given list, make all possible combinations and chain them together as one object.

这篇关于列表的Python Power Set的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆