2

To clarify, my original list contains the difference between two consecutive values, starting from zero. I want to convert this list to a list of actual values using a functional style, without having to keep a global state during calculation, without for loops, using map, reduce, etc.

my_list = [0, 1, 0, 3, 2, 0, 0, 2, 1]
result = my_function(my_list)

print(result)

[0, 1, 1, 4, 6, 6, 6, 8, 9]
kureta
  • 478
  • 4
  • 15

2 Answers2

4

Just use itertools.accumulate.

u354356007
  • 3,205
  • 15
  • 25
  • wow! this is awesome, thanks. – kureta Nov 07 '15 at 10:10
  • is there an inverse of this function that will output my_list given the result list? – kureta Nov 07 '15 at 18:23
  • @kureta `itertools.starmap(operator.sub, zip(a, [0] + a))`, but please, don't use this code anywhere. This is clearly not the pythonic way. Unclear, error-prone, dense. – u354356007 Nov 07 '15 at 23:10
  • how about this? `def differences(seq):` `iterable, copied = tee(seq)` `next(copied)` `for x, y in zip(iterable, copied):` `yield y - x – kureta Nov 08 '15 at 11:59
3
def my_function(lst):
    return [sum(lst[:i]) for i in range(len(lst))]
Ozgur Vatansever
  • 49,246
  • 17
  • 84
  • 119