본문으로 바로가기

[itertools] accumulate()

category Programming Language/Python 2022. 8. 24. 22:40

itertools

Functions creating iterators for efficient looping

 

itertools.accumulate()

Make an iterator that returns accumulated sums, or accumulated results of other binary functions (specified via the optional func argument)

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

Using accumulate()

import itertools  
import operators

arr = [1, 2, 3, 4, 5]  

# prints the successive summation of elements
print(list(itertools.accumulate(arr))) # [1, 3, 6, 10, 15]

# prints the successive multiplication of elements
print(list(itertools.accumulate(arr, operator.mul)) # [1, 2, 6, 24, 120]

# prints the successive summation of elements with an initial value
print(list(itertools.accumulate(arr, initial=10))) # [11, 13, 16, 20, 35]

# prints the successive maximum of elements
print(list(itertools.accumulate(arr, max))) # [1, 2, 3, 4, 5]

customized func

import itertools

# select tuple base on second value, then first value
def select(a, b):
    ta = (a[1], a[0])
    tb = (b[1], b[0])
    if ta>=tb:
        return a
    return b

tlist = [(1, 3), (2, 5), (1, 7), (6, 3), (1, 7), (3, 4)] 

# prints the bigger tuples with a customized function
print(list(itertools.accumulate(tlist, select))) # [(1, 3), (2, 5), (1, 7), (1, 7), (1, 7), (1, 7)]

Reference

[python docs] https://docs.python.org/3/library/itertools.html
[geeksforgeeks] https://www.geeksforgeeks.org/python-itertools/

'Programming Language > Python' 카테고리의 다른 글

[built-in] map()  (0) 2022.08.25