Cumulative Operations using itertools¶
Get cumulative sales from list of transactions.
In [1]:
ns = [1, 2, 3, 4]
# Cumulative totals [1, 3, 6, 10]
# Cumulative product [1, 2, 6, 24]
In [2]:
import itertools as iter
In [3]:
iter.accumulate?
Init signature: iter.accumulate(iterable, func=None, *, initial=None) Docstring: Return series of accumulated sums (or other binary function results). Type: type Subclasses:
In [4]:
iter.accumulate(ns)
Out[4]:
<itertools.accumulate at 0x7f9041d8de80>
In [5]:
list(iter.accumulate(ns))
Out[5]:
[1, 3, 6, 10]
In [6]:
import operator as o
list(iter.accumulate(ns, o.mul))
Out[6]:
[1, 2, 6, 24]
In [7]:
sales = [
(202101, 10500),
(202102, 11250),
(202103, 13450),
(202104, 8500),
(202105, 9250),
(202106, 8760),
(202107, 12150),
(202108, 11850),
(202109, 10950),
(202110, 9250),
(202111, 14250),
(202112, 13650),
]
In [8]:
sales
Out[8]:
[(202101, 10500), (202102, 11250), (202103, 13450), (202104, 8500), (202105, 9250), (202106, 8760), (202107, 12150), (202108, 11850), (202109, 10950), (202110, 9250), (202111, 14250), (202112, 13650)]
In [9]:
sale_months = map(lambda sale: sale[0], sales)
In [10]:
list(sale_months)
Out[10]:
[202101, 202102, 202103, 202104, 202105, 202106, 202107, 202108, 202109, 202110, 202111, 202112]
In [11]:
sale_revenues = map(lambda sale: sale[1], sales)
In [12]:
list(sale_revenues)
Out[12]:
[10500, 11250, 13450, 8500, 9250, 8760, 12150, 11850, 10950, 9250, 14250, 13650]
In [13]:
cumulative_revenues = list(iter.accumulate(map(lambda sale: sale[1], sales)))
In [14]:
cumulative_revenues
Out[14]:
[10500, 21750, 35200, 43700, 52950, 61710, 73860, 85710, 96660, 105910, 120160, 133810]
In [15]:
sale_months = map(lambda sale: sale[0], sales)
sale_revenues = map(lambda sale: sale[1], sales)
cumulative_revenues = list(iter.accumulate(map(lambda sale: sale[1], sales)))
list(zip(sale_months, cumulative_revenues))
Out[15]:
[(202101, 10500), (202102, 21750), (202103, 35200), (202104, 43700), (202105, 52950), (202106, 61710), (202107, 73860), (202108, 85710), (202109, 96660), (202110, 105910), (202111, 120160), (202112, 133810)]