I have a sorteddict
and I am interested in the cumulative sum of the 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 frequently need to update the dictionary and so need to recalculate the cumulative sum:
>>> 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'm wondering whether instead of constantly recalculating the cumulative sum, there is some clever way of maintaining the cumulative sum efficiently?
Note
>>> import sys
>>> sys.version
'2.7.11 (default, Jun 15 2016, 17:53:20) [MSC v.1800 32 bit (Intel)]'
Also in general my keys and values will not be the same -- I was just lazy in my example