accumulate.py 579 B

123456789101112131415161718192021
  1. # Copyright PSF
  2. """
  3. Python 2 implementation of the accumulate function in itertools
  4. From the Python documentation https://docs.python.org/3/library/itertools.html#itertool-functions
  5. """
  6. import operator
  7. def accumulate(iterable, func=operator.add):
  8. 'Return running totals'
  9. # accumulate([1,2,3,4,5]) --> 1 3 6 10 15
  10. # accumulate([1,2,3,4,5], operator.mul) --> 1 2 6 24 120
  11. it = iter(iterable)
  12. try:
  13. total = next(it)
  14. except StopIteration:
  15. return
  16. yield total
  17. for element in it:
  18. total = func(total, element)
  19. yield total