# Create a new list by summing elements inside the sublists of a list

Let's say I have a list with all partitions of 5:

{{5}, {4, 1}, {3, 2}, {3, 1, 1}, {2, 2, 1}, {2, 1, 1, 1}, {1, 1, 1, 1, 1}}


I want to create a new list that has as sublists the combination of summing two elements of the sublists of the original list, avoiding duplications. So for example, for the lists of partitions of 5, the list I want to create is:

{
{5}, {4+1}, {3+2}, {{3+1, 1}, {3, 1+1}}, {{2+2, 1}, {2, 2+1}},
{{2+1, 1, 1}, {2, 1+1, 1}}, {1+1, 1, 1, 1}
}


Which is:

{{5}, {5}, {5}, {{4, 1}, {3, 2}}, {{4, 1}, {3, 2}}, {{3, 1, 1}, {2, 2, 1}},
{2, 1, 1, 1}}


I would appreciate it very much if someone could help me to create this.

• You said that you want to avoid duplicates but the result in your example contains duplicates... Commented Aug 31, 2019 at 18:19
• On what condition do you stop summing pairs in the sublists? Also, what have you tried and what is not working? Commented Aug 31, 2019 at 19:40

ClearAll[f, f0, f1, f2]


Distinct two-subsets

f0[x_] := DeleteDuplicates[Subsets[x, {2}]]


Delete elements of y once:

f1[x_, y_] := Fold[DeleteCases[x, y, 1, 1] &, x, y] &;


Sum of a two-subset combined with remaining elements:

f2[x_] := Join[{Total[#]}, f1[x, #]] & /@ f0[x]


If x has 1 or 2 elements just take the sum otherwise process using f2:

f[x_] := If[Length@x <= 2, {Total[x]}, f2[x]]


Examples:

lst = IntegerPartitions[5]


{{5}, {4, 1}, {3, 2}, {3, 1, 1}, {2, 2, 1}, {2, 1, 1, 1}, {1, 1, 1, 1, 1}}

f @ lst


{{5}, {5}, {5}, {{4, 1}, {2, 3}}, {{4, 1}, {3, 2}}, {{3, 1, 1}, {2, 2, 1}}, {{2, 1, 1, 1}}}

which matches the desired result except ordering of sub-sublists.

lst2 = IntegerPartitions[4]


{{4}, {3, 1}, {2, 2}, {2, 1, 1}, {1, 1, 1, 1}}

f @ lst2


{{4}, {4}, {4}, {{3, 1}, {2, 2}}, {{2, 1, 1}}}