TransWikia.com

Summing list elements for given index tuple

Mathematica Asked on July 18, 2021

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.

One Answer

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}

Answered by kglr on July 18, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP