所有子集的集合

发布于 2025-01-08 20:31:28 字数 244 浏览 3 评论 0原文

在 Python2 中,我可以用来

def subsets(mySet):
    return reduce(lambda z, x: z + [y + [x] for y in z], mySet, [[]])

查找 mySet 的所有子集。 Python 3 已删除reduce

对于 Python3 来说,同样简洁的重写是什么?

In Python2 I could use

def subsets(mySet):
    return reduce(lambda z, x: z + [y + [x] for y in z], mySet, [[]])

to find all subsets of mySet. Python 3 has removed reduce.

What would be an equally concise rewrite of this for Python3?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

栖迟 2025-01-15 20:31:28

下面是 Python 中幂集(所有子集的集合)算法的几种可能实现的列表。有些是递归的,有些是迭代的,有些不使用reduce。有很多选项可供选择!

Here's a list of several possible implementations of the power set (the set of all subsets) algorithm in Python. Some are recursive, some are iterative, some of them don't use reduce. Plenty of options to choose from!

晚雾 2025-01-15 20:31:28

函数reduce() 始终可以被for 循环替换。下面是 reduce() 的 Python 实现:(

def reduce(function, iterable, start=None):
    iterator = iter(iterable)
    if start is None:
        start = next(iterator)
    for x in iterator:
        start = function(start, x)
    return start

与 Python 内置版本的 reduce() 相比,该版本不允许传入 None< /code> 作为 start 参数。)

将此代码与传递给 reduce() 的参数进行特殊封装可以得到

def subsets(my_set):
    result = [[]]
    for x in my_set:
        result = result + [y + [x] for y in result]
    return result

The function reduce() can always be reaplaced by a for loop. Here's a Python implementation of reduce():

def reduce(function, iterable, start=None):
    iterator = iter(iterable)
    if start is None:
        start = next(iterator)
    for x in iterator:
        start = function(start, x)
    return start

(In contrast to Python's built-in version of reduce(), this version does not allow to pass in None as start parameter.)

Special-casing this code with the parameters you passed to reduce() gives

def subsets(my_set):
    result = [[]]
    for x in my_set:
        result = result + [y + [x] for y in result]
    return result
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文