How to add numbers in your list, incrementally, while also being sorted from lowest to highest value?

79 views Asked by At

I'm trying to write code to firstly, order numbers from lowest to highest (e.g. 1, 3, 2, 4, 5 to 1, 2, 3, 4, 5). Secondly, I would like to incrementally add the numbers in the list. eg.

1
3
6
10
15

I've already tried using the sum function, then the sorted function, but I was wondering if I can write them neatly in a code to just get everything worked out.

Addition = [1, 13, 166, 3, 80, 6, 40]
print(sorted(Addition))

I was able to get the numbers sorted horizontally, but I wasn't able to get the numbers added vertically.

2

There are 2 answers

0
iz_ On BEST ANSWER

You can use itertools.accumulate with sorted:

import itertools

mylist = [1, 2, 3, 4, 5]
result = list(itertools.accumulate(sorted(mylist)))
# result: [1, 3, 6, 10, 15]

The default action is operator.add, but you can customize it. For example, you can do running product instead of running sum if you needed it:

import itertools
import operator

mylist = [1, 2, 3, 4, 5]
result = list(itertools.accumulate(sorted(mylist), operator.mul))
# result: [1, 2, 6, 24, 120]
4
rafaelc On

Apparently, you need a cumulative addition. You can code a simple one using a simple loop and yield the results on the go

def cumulative_add(array):
    total = 0
    for item in array:
        total += item
        yield total


>>> list(cumulative_add([1,2,3,4,5]))
[1, 3, 6, 10, 15]

Depending on your goals, you may also wish to use a library, such as pandas, that has cumulative sum already written for you.

For example,

>>> s = pd.Series([1,2,3,4,5])
>>> s.cumsum()

0     1
1     3
2     6
3    10
4    15