简体   繁体   中英

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.
Example
[1,2,3,4,100]
return [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:])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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