Efficient one-liner in Julia to calculate "running" sums? -
is there efficient way following in julia in 1 line of code?
foldl((prev, x)-> [prev; prev[end] + x] , 0, block_lengths)
for example,
block_lengths = [2, 2, 2, 2, 3]
the desired output is
[0, 2, 4, 6, 8, 11]
(i presume way used foldl
above inefficient, because i'm concatenating vector , integer @ each iteration.)
iiuc, can use cumsum
:
julia> block_lengths = [2, 2, 2, 2, 3]; julia> cumsum(block_lengths) 5-element array{int32,1}: 2 4 6 8 11 julia> [0; cumsum(block_lengths)] 6-element array{int32,1}: 0 2 4 6 8 11
which should o(n).
Comments
Post a Comment