-1

I'm sorry the title is very confusing because it's already kind of confusing to think about how to say it in my native language.

An example will be far more clear than I can be with sentences:

Let's say I have a list:

l = [1, 2, 3]

I want my output to look like this:

out = [ [1, 2, 3], [3, 3], [1, 5], [4, 2], [6] ]

So basically, you make this list:

[    l, [ l[0]+l[1], l[2] ], [ l[0], l[1]+l[2] ], [ l[0]+l[2], l[1] ], [ l[0]+l[1]+l[2] ]    ]

I've already found a way to do this, it's an ugly function and I was wondering if there was a beautiful, pythonic way to do this. I thought about using functools.reduce() but can't wrap my head around how to do this.

Thanks in advance.

Vi Barb
  • 13
  • 2
  • Maybe this can help: [https://stackoverflow.com/questions/19368375/set-partitions-in-python](https://stackoverflow.com/questions/19368375/set-partitions-in-python) – kubatucka Jun 16 '20 at 14:55

1 Answers1

0

You can use combinations from itertools

from itertools import combinations

l = [1,2,3]
res = [l]
for i in list(combinations(l, 2)):
      value = 0
      for inx in i:
            value += l[inx-1]
      res.append([value, l[sum(set(l) - set(i)) - 1]])
res.append([sum(l)])
print(res)

Output

[[1, 2, 3], [3, 3], [4, 2], [5, 1], [6]]

The direction of the list is a bit different then the example but I hope it's helping you.

Leo Arad
  • 4,452
  • 2
  • 6
  • 17