简体   繁体   English

使用列表推导和递归的列表所有子集的Python Sum

[英]Python Sum of all subset of list using list comprehension and recursion

I'm trying to write a program that returns set of all subset sum of a list. 我正在尝试编写一个程序,该程序返回列表的所有子集和的集合。 I must use list comprehension and recursion. 我必须使用列表理解和递归。

Example: 例:

[1,2,3,10]
return set([0,1,2,3,4,5,6,100,101,102,103,104,105,106])

I write code: 我写代码:

def function(L):
    if len(L) == 0:
        return []
    return list((L[index] + rest) for index in range(len(L)) for rest in function(L[:index])+L[index+1:])

This code returns sum of subsets but only 2 or more elemental subset. 此代码返回子集的总和,但仅返回2个或更多基本子集。
Example
[1,2,3,4,100] [1,2,3,4,100]
return [3,4,5,6,101,102,103,104,105,106] 返回[3,4,5,6,101,102,103,104,105,106]

This is change that seems to yield the right answer: 这是似乎产生正确答案的变化:

def function(L):
 if len(L) == 0:return []
 return L+list((L[index] + rest) for index in range(len(L)) for rest in function(L[:index])+L[index+1:])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM