Python递归函数显示给定集合的所有子集 [英] Python recursive function to display all subsets of given set

查看:18
本文介绍了Python递归函数显示给定集合的所有子集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下 python 函数来打印数字列表的所有子集:

def subs(l):如果 len(l) == 1:返回 [l]资源 = []对于 subs(l[0:-1]) 中的 sub:res.append(sub)res.append([l[-1]])res.append(sub+[l[-1]])返回资源li = [2, 3, 5, 8]打印(订阅(li))

返回:

[[2], [8], [2, 8], [5], [8], [5, 8], [2, 5], [8], [2, 5,8], [3], [8], [3, 8], [5], [8], [5, 8], [3, 5], [8], [3, 5, 8], [2, 3, [8], [2, 3, 8], [5], [8], [5, 8], [2, 3, 5], [8], [2, 3, 5,8]]]

这不是预期的答案.看起来 python 通过引用将列表 l 带入函数中.因此,当我附加 l[-1] 时,它会附加原始列表的最后一个元素,而不是发送到递归方法中的较小列表.有什么办法可以解决这个问题吗?

这可能可以使用元组解决,但我想知道是否有使用列表的解决方案.

解决方案

def subs(l):如果 l == []:返回 [[]]x = subs(l[1:])返回 x + [[l[0]] + y for y in x]

结果:

<预><代码>>>>打印 (subs([1, 2, 3]))[[], [3], [2], [2, 3], [1], [1, 3], [1, 2], [1, 2, 3]]

I have the following python function to print all subsets of a list of numbers:

def subs(l):
    if len(l) == 1:
        return [l]
    res = []
    for sub in subs(l[0:-1]):
        res.append(sub)
        res.append([l[-1]])
        res.append(sub+[l[-1]])
    return res

li = [2, 3, 5, 8]
print(subs(li))

This returns:

[[2], [8], [2, 8], [5], [8], [5, 8], [2, 5], [8], [2, 5, 8], [3], [8], [3, 8], [5], [8], [5, 8], [3, 5], [8], [3, 5, 8], [2, 3], [8], [2, 3, 8], [5], [8], [5, 8], [2, 3, 5], [8], [2, 3, 5, 8]]

Which is not the expected answer. It looks like python takes the list l into the function by reference. So when I append l[-1], it appends the last element of original list, not the smaller list sent into the recursive method. Is there any way to solve this?

This could possibly be solved using tuples but I'm wondering if there is a solution using lists.

解决方案

def subs(l):
    if l == []:
        return [[]]

    x = subs(l[1:])

    return x + [[l[0]] + y for y in x]

Results:

>>> print (subs([1, 2, 3]))
[[], [3], [2], [2, 3], [1], [1, 3], [1, 2], [1, 2, 3]]

这篇关于Python递归函数显示给定集合的所有子集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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