Help Needed with Cumulative Sum Calculation with Code Block or nodes


Hi everyone,

I’m currently working on a project in Dynamo where I need to calculate the cumulative sum of a list of numbers. I have set up a Code Block to perform the calculation using an imperative block, but it’s returning an empty list despite my attempts to troubleshoot. Is there any other way to achive results of first code block in more practical way ?

I had the same issue, I chose the easy way and did it in python :sweat_smile:
Anyway, maybe this one helps:

I don’t have the slightest idea why does it work with flatten, but it still does not work with sublists.

A solution with nodes:


A solution with design script - there is no reason to perform imperative here:

Design Script
Math.Sum(List.DropItems(lst, -List.Count(lst)+1..0));

A solution with Python:

Python Script
values = IN[0]
runningVal = 0
totals = []
for v in values:
    runningVal+=v
    totals.append(runningVal)
OUT = totals

A solution using imperative code in design script:

Imperative Design Script
lst;
runningVal = 0;
sums = [];
[Imperative]
{
	for (i in lst)
	{
		runningVal = runningVal+i;
		sums = List.AddItemToEnd(runningVal, sums);
	}
	return = sums;
};

I think that covers all the bases.

If you need to do this on lists of lists adjust the lacing as required (@L2<1L> in design script, for list in lists in imperative and Python, and list levels when using nodes).

7 Likes

Thank you

1 Like