ID EN
Itertools

accumulate

Python 3.11 🇮🇩 Bahasa Indonesia

Buat iterator yang mengembalikan jumlah akumulasi atau hasil akumulasi dari fungsi biner lainnya.

Syntax

PYTHON
itertools.accumulate(iterable[, func, *, initial=None])

Contoh

Example 1
PYTHON
def accumulate(iterable, func=operator.add, *, initial=None):
    'Return running totals'
     accumulate([1,2,3,4,5]) --> 1 3 6 10 15
     accumulate([1,2,3,4,5], initial=100) --> 100 101 103 106 110 115
     accumulate([1,2,3,4,5], operator.mul) --> 1 2 6 24 120
    it = iter(iterable)
    total = initial
    if initial is None:
        try:
            total = next(it)
        except StopIteration:
            return
    yield total
    for element in it:
        total = func(total, element)
        yield total
Example 2
PYTHON
>>> data = [3, 4, 6, 2, 1, 9, 0, 7, 5, 8]
>>> list(accumulate(data, operator.mul))      running product
[3, 12, 72, 144, 144, 1296, 0, 0, 0, 0]
>>> list(accumulate(data, max))               running maximum
[3, 4, 6, 6, 6, 9, 9, 9, 9, 9]

 Amortize a 5% loan of 1000 with 4 annual payments of 90
>>> cashflows = [1000, -90, -90, -90, -90]
>>> list(accumulate(cashflows, lambda bal, pmt: bal*1.05 + pmt))
[1000, 960.0, 918.0, 873.9000000000001, 827.5950000000001]

See Also

Decimal Fraction min() max() operator.mul() functools.reduce()