8

I have a list, for example:

data = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20};

and I wanted to sum every element in range of five, i. e

ranges

{1,2,3,4,5} and {6,7,8,9,10} and {11,12,13,14,15} and {16,17,18,19,20}

and the result I want to get is:

{34, 38, 42, 46, 50}

4 Answers4

7

There are three ways that yield the desired outut: 1. Last@Accumulate@list Plus@@list and Total@list


Various approaches to get the list mentioned above


0. Internal`PartitionRagged

Last@Accumulate@
  Internal`PartitionRagged[data, Table[5, Length@data/5]]

also

Plus @@ Internal`PartitionRagged[data, Table[5, Length@data/5]]

and

Total@Internal`PartitionRagged[data, 
   Table[5, Length@data/5]]

1. ArrayReshape

Last@Accumulate@ArrayReshape[data, {Length@data/5, 5}]

also

Plus @@ ArrayReshape[data, {Length@data/5, 5}]

and

Total@ArrayReshape[data, {Length@data/5, 5}]

2. Fold + Partition + Flatten

Last@Accumulate@
  Fold[Partition, Flatten[data], {Length@data/5, 5}[[-1 ;; 2 ;; -1]]]

also

Plus @@ Fold[Partition, 
  Flatten[data], {Length@data/5, 5}[[-1 ;; 2 ;; -1]]]

and

Total@Fold[Partition, 
  Flatten[data], {Length@data/5, 5}[[-1 ;; 2 ;; -1]]]

3. TakeList

Last@Accumulate@TakeList[data, Table[5, Length@data/5]]

also

Plus @@ TakeList[data, Table[5, Length@data/5]]

and

Total@TakeList[data, Table[5, Length@data/5]]

4. FoldPairList + TakeDrop

Last@Accumulate@FoldPairList[TakeDrop, data, Table[5, Length@data/5]]

also

Plus @@ FoldPairList[TakeDrop, data, Table[5, Length@data/5]]

and

Total@FoldPairList[TakeDrop, data, Table[5, Length@data/5]]

All of the above and the solutions suggested in the comments section give

lisres

I will update the timings later tonight

bmf
  • 15,157
  • 2
  • 26
  • 63
3
data = Range[20];

Using MovingMap:

Total@MovingMap[# &, data, 4][[1 ;; -1 ;; 5]]

({34, 38, 42, 46, 50})

Or using BlockMap:

Total@BlockMap[# &, data, 5]

(({34, 38, 42, 46, 50}))

E. Chan-López
  • 23,117
  • 3
  • 21
  • 44
1
data = Range[20];

Using SequenceCases

Total @ SequenceCases[data, {Repeated[_, {5}]}]

{34, 38, 42, 46, 50}

Total @ SequenceCases[data, _?(Length[#] == 5 &)]

{34, 38, 42, 46, 50}

eldo
  • 67,911
  • 5
  • 60
  • 168
1

Using ArrayReduce and Partition:

data = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18,
    19, 20};

Partition[data, 5] // ArrayReduce[Total, #, 1] &


Using MapThread:

MapThread[Plus@## &, Partition[data, 5]]

Result:

{34, 38, 42, 46, 50}

Syed
  • 52,495
  • 4
  • 30
  • 85