3
$\begingroup$

Is there a more compact way of summing certain elements of lists together when given a tuple of which elements to sum. For example if I am given the list of size 8:

{1,2,3,4,5,6,7,8}

and a sequence which indicates which elements to sum together, such as (1,3,3,1), this should yield

{1, 9, 18, 8}

I was considering further (1,3,3,1) partitioning of the original list {1,2,3,4,5,6,7,8} and then simply adding the entries at that level? Is there a clear way of doing this further (1,3,3,1) partitioning?

Thanks for any assistance.

$\endgroup$
3
  • 4
    $\begingroup$ Try: Total /@ TakeList[{1, 2, 3, 4, 5, 6, 7, 8}, {1, 3, 3, 1}] $\endgroup$ May 11, 2021 at 9:15
  • 1
    $\begingroup$ Or Total[TakeList[lst,{1,3,3,1}],{2}] $\endgroup$
    – user1066
    May 11, 2021 at 9:41
  • $\begingroup$ Great answers thanks! $\endgroup$
    – John Doe
    May 11, 2021 at 9:43

1 Answer 1

1
$\begingroup$
FoldPairList[TakeDrop, {1, 2, 3, 4, 5, 6, 7, 8}, {1, 3, 3, 1}, Total @ *First]
{1, 9, 18, 8}

Alternatively,

FoldPairList[{Total @ Take @ ##, Drop @ ##} &, {1, 2, 3, 4, 5, 6, 7, 8}, {1, 3, 3, 1}]
 {1, 9, 18, 8}
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.