How to save the cumulative amount?

I have sorteddictand am interested in the cumulative sum of values:

>>> from blist import sorteddict
>>> import numpy as np
>>> x = sorteddict({1:1, 2:2, 5:5})
>>> zip(x.keys(), np.cumsum(x.values())) 
[(1, 1), (2, 3), (5, 8)]

However, I often need to update the dictionary and therefore I need to recalculate the total amount:

>>> x[4] = 4
>>> zip(x.keys(), np.cumsum(x.values()))
[(1, 1), (2, 3), (4, 7), (5, 12)]

>>> x[3] = 3
>>> zip(x.keys(), np.cumsum(x.values()))
[(1, 1), (2, 3), (3, 6), (4, 10), (5, 15)]

I wonder if, instead of constantly recalculating the total amount, is it possible to effectively use the cumulative amount?

Note

>>> import sys
>>> sys.version
'2.7.11 (default, Jun 15 2016, 17:53:20) [MSC v.1800 32 bit (Intel)]'

In general, my keys and values ​​will not be the same - I was just lazy in my example

+4
source share

Source: https://habr.com/ru/post/1676056/


All Articles