#!/usr/bin/python3 def accumulate(iterable): '''Return running totals accumulate([1, 2, 3, 4, 5]) --> 1 3 6 10 15 accumulate() is the inverse function of decumulate() accumulate(decumulate(x)) == decumulate(accumulate(x)) == x''' items = iter(iterable) total = next(items) yield total for item in items: total += item yield total def decumulate(iterable): '''Return running differences decumulate([1, 3, 6, 10, 15]) --> 1 2 3 4 5 decumulate() is the inverse function of accumulate() decumulate(accumulate(x)) == accumulate(decumulate(x)) == x''' items = iter(iterable) previous = next(items) yield previous for item in items: yield item - previous previous = item if __name__ == '__main__': print(list(accumulate(range(10, 20)))) print(list(decumulate(range(10, 20)))) print(list(accumulate(decumulate(range(10, 20))))) print(list(decumulate(accumulate(range(10, 20))))) ## [10, 21, 33, 46, 60, 75, 91, 108, 126, 145] ## [10, 1, 1, 1, 1, 1, 1, 1, 1, 1] ## [10, 11, 12, 13, 14, 15, 16, 17, 18, 19] ## [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]